huma icon indicating copy to clipboard operation
huma copied to clipboard

How can one secure the docs endpoint?

Open betaprior opened this issue 7 months ago • 1 comments

It would be nice to have some documented options for securing the docs endpoint; I used my router middleware to provide basic auth just for the /docs route, but wasn't sure if it's the only/best option available.

betaprior avatar Jul 01 '25 09:07 betaprior

I use this pattern

func UseSecurity(g *huma.Group, scheme string) {
	g.UseSimpleModifier(func(o *huma.Operation) {
		if len(o.Security) == 0 {
			o.Security = []map[string][]string{{scheme: {}}}
		}
	})
}
func HumaAuthMiddleware(g *huma.Group) func(huma.Context, func(huma.Context)) {
	routes.UseSecurity(g, "bearerAuth")
	return wrapHTTPMiddleware(AuthMiddleware)
}
cfgInfo := huma.DefaultConfig("Project Template API", "0.1rc")
cfgInfo.OpenAPI.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
	routes.BearerScheme: {
		Type:         "http",
		Scheme:       "bearer",
		BearerFormat: "JWT",
	},
}
	 items.UseMiddleware(middleware.HumaAuthMiddleware(items))

You can fine tune it to make work best for you. By utilizing factory pattern, you can make it more clean. I'm still working on improving this. I hope this can give you some idea how to implement it.

MeGaNeKoS avatar Aug 02 '25 14:08 MeGaNeKoS