diff --git a/docs/docs/how-to/oauth2-jwt.md b/docs/docs/how-to/oauth2-jwt.md index c996b839..3b8fd16c 100644 --- a/docs/docs/how-to/oauth2-jwt.md +++ b/docs/docs/how-to/oauth2-jwt.md @@ -147,7 +147,7 @@ func NewJWKSet(jwkUrl string) jwk.Set { // NewAuthMiddleware creates a middleware that will authorize requests based on // the required scopes for the operation. -func NewAuthMiddleware(jwksURL string) { +func NewAuthMiddleware(api huma.API, jwksURL string) func(ctx huma.Context, next func(huma.Context)) { keySet := NewJWKSet(jwksURL) return func(ctx huma.Context, next func(huma.Context)) { @@ -168,7 +168,7 @@ func NewAuthMiddleware(jwksURL string) { token := strings.TrimPrefix(ctx.Header("Authorization"), "Bearer ") if len(token) == 0 { - huma.WriteErr(ctx, http.StatusUnauthorized, "Unauthorized") + huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized") return } @@ -180,20 +180,22 @@ func NewAuthMiddleware(jwksURL string) { jwt.WithAudience("my-audience"), ) if err != nil { - huma.WriteErr(ctx, http.StatusUnauthorized, "Unauthorized") + huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized") return } // Ensure the claims required for this operation are present. - scopes = parsed.Get("scopes").([]string) - for _ scope := range scopes { - if slices.Contains(anyOfNeededScopes, scope) { - next(ctx) - return + scopes, _ := parsed.Get("scopes") + if scopes, ok := scopes.([]string); ok { + for _, scope := range scopes { + if slices.Contains(anyOfNeededScopes, scope) { + next(ctx) + return + } } } - huma.WriteErr(ctx, http.StatusForbidden, "Forbidden") + huma.WriteErr(api, ctx, http.StatusForbidden, "Forbidden") } } ``` @@ -201,7 +203,7 @@ func NewAuthMiddleware(jwksURL string) { Lastly, when configuring your API, be sure to include this middleware: ```go title="main.go" -api.UseMiddleware(NewAuthMiddleware("https://example.com/.well-known/jwks.json")) +api.UseMiddleware(NewAuthMiddleware(api, "https://example.com/.well-known/jwks.json")) ``` ### Supporting different Token Formats