From 7cd0fb15e83cb5824a0c297a75a20d08a754ce8e Mon Sep 17 00:00:00 2001 From: Marcin Romaszewicz Date: Tue, 7 Jul 2026 16:02:05 -0700 Subject: [PATCH] Deprecate ctx based security scopes Generated server code no longer embeds security scheme scopes into the request context. The per-scheme context key types (e.g. `bearerAuthContextKey`), scope constants (e.g. `BearerAuthScopes`), and per-operation context stores flattened the spec's `security` requirements and could not represent alternative (OR), combined (AND), or anonymous (`{}`) schemes. Authentication should instead use the request validation middleware, which evaluates the spec's security requirements directly. See #1524. - Add `compatibility.enable-auth-scopes-on-context` (default off) to restore the legacy emission, and document it in the README and configuration schema - Gate all emission sites on the new option: security scheme context key types, scope constants, and the context stores in the chi, gorilla, stdhttp, echo, echo/v5, iris, fiber, and gin templates - Opt the fiber middleware fixture into the option so the issue-518 anonymous-alternative regression stays meaningful; its generated output is unchanged - Add TestEnableAuthScopesOnContext covering both option states - Regenerate; affected fixtures and examples lose only the now-dead scope artifacts. The authenticated-api examples already authenticate via the validation middleware and are otherwise unaffected --- README.md | 23 ++++++-- configuration-schema.json | 4 ++ .../authenticated-api/echo/api/api.gen.go | 11 ---- .../authenticated-api/stdhttp/api/api.gen.go | 19 ------- internal/test/aggregates/anyof/anyof.gen.go | 15 ------ internal/test/clients/clients.gen.go | 7 --- .../identifiers/identifiers_schemas.gen.go | 13 ----- .../multipackage/petstore/petstore.gen.go | 11 ---- .../multipackage/pruned_deps/api.gen.go | 3 -- .../test/servers/middleware/fiber/config.yaml | 5 ++ pkg/codegen/codegen.go | 9 ++-- pkg/codegen/codegen_test.go | 53 +++++++++++++++++++ pkg/codegen/configuration.go | 14 +++++ pkg/codegen/templates/chi/chi-middleware.tmpl | 2 +- pkg/codegen/templates/constants.tmpl | 2 +- pkg/codegen/templates/echo/echo-wrappers.tmpl | 2 + .../templates/echo/v5/echo-wrappers.tmpl | 2 + .../templates/fiber/fiber-middleware.tmpl | 2 + pkg/codegen/templates/gin/gin-wrappers.tmpl | 2 + .../templates/gorilla/gorilla-middleware.tmpl | 2 +- .../templates/iris/iris-middleware.tmpl | 2 + .../stdhttp/std-http-middleware.tmpl | 2 +- 22 files changed, 115 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index 8914ddaf2a..16647786dd 100644 --- a/README.md +++ b/README.md @@ -3347,13 +3347,28 @@ If you're using a specification with [Security Schemes](https://spec.openapis.or > [!NOTE] > Out-of-the-box, the server-side code generated by `oapi-codegen` does not provide security validation. > -> To perform authentication, you will need to use the [validation middleware](#requestresponse-validation-middleware). +> To perform authentication, you will need to use the [validation middleware](#requestresponse-validation-middleware), which validates each request against the spec's security requirements and calls your `AuthenticationFunc` with the scheme name and required scopes. To see how this can work, check out the [authenticated API example](examples/authenticated-api/echo). -If an operation includes an empty `{}` security alternative, generated server -middleware treats that operation as allowing anonymous requests and doesn't embed required -security scopes in the request context. +#### Deprecated: auth scopes on the request context + +Historically, generated server code embedded each operation's security scopes into the request context: +a context key type per security scheme (e.g. `bearerAuthContextKey`), a scope constant (e.g. `BearerAuthScopes`), +and a per-operation call storing the operation's scopes into the request context. + +This mechanism is deprecated and no longer generated by default. It flattens the +spec's `security` requirements into a per-scheme list of scopes, and cannot represent +alternative schemes (OR), combined schemes (AND), or anonymous (`{}`) alternatives, so middleware built on it can't correctly enforce the spec. Use the [validation middleware](#requestresponse-validation-middleware) instead. Please see [#1524](https://github.com/oapi-codegen/oapi-codegen/issues/1524) for more background. + +If you have existing middleware that relies on these constants, you can re-enable them with: + +```yaml +compatibility: + enable-auth-scopes-on-context: true +``` + +Note that even when re-enabled, an operation that includes an empty `{}` security alternative allows anonymous requests, and no scopes are embedded into the request context for that operation. ### On the client diff --git a/configuration-schema.json b/configuration-schema.json index 1608987f5e..c9c18c7968 100644 --- a/configuration-schema.json +++ b/configuration-schema.json @@ -127,6 +127,10 @@ "headers-implicitly-required": { "type": "boolean", "description": "Treats all response headers as required, ignoring the `required` property from the header definition. Prior to v2.6.0, oapi-codegen generated all response headers as direct values (implicitly required). The OpenAPI specification defaults headers to optional (required: false), so the corrected behavior generates optional headers as pointers. Set this to true to restore the old behavior where all headers are treated as required.\nPlease see https://github.com/oapi-codegen/oapi-codegen/issues/2267" + }, + "enable-auth-scopes-on-context": { + "type": "boolean", + "description": "Re-enables the legacy emission of security scheme scopes by generated server code: the per-scheme context key types (e.g. `bearerAuthContextKey`), the scope constants (e.g. `BearerAuthScopes`), and the per-operation calls that store the operation's scopes into the request context.\nThis mechanism is deprecated and off by default: it flattens the OpenAPI `security` requirements into a per-scheme list of scopes, and cannot represent alternative schemes (OR), combined schemes (AND), or anonymous (`{}`) alternatives. Authentication and authorization should instead be performed at runtime using the request validation middleware, which evaluates the spec's security requirements directly.\nPlease see https://github.com/oapi-codegen/oapi-codegen/issues/1524" } } }, diff --git a/examples/authenticated-api/echo/api/api.gen.go b/examples/authenticated-api/echo/api/api.gen.go index d2d5bd4006..f3e295736c 100644 --- a/examples/authenticated-api/echo/api/api.gen.go +++ b/examples/authenticated-api/echo/api/api.gen.go @@ -20,10 +20,6 @@ import ( "github.com/labstack/echo/v4" ) -const ( - BearerAuthScopes bearerAuthContextKey = "BearerAuth.Scopes" -) - // Error defines model for Error. type Error struct { // Code Error code @@ -44,9 +40,6 @@ type ThingWithID struct { Name string `json:"name"` } -// bearerAuthContextKey is the context key for BearerAuth security scheme -type bearerAuthContextKey string - // AddThingJSONRequestBody defines body for AddThing for application/json ContentType. type AddThingJSONRequestBody = Thing @@ -534,8 +527,6 @@ type ServerInterfaceWrapper struct { func (w *ServerInterfaceWrapper) ListThings(ctx echo.Context) error { var err error - ctx.Set(string(BearerAuthScopes), []string{}) - // Invoke the callback with all the unmarshaled arguments err = w.Handler.ListThings(ctx) return err @@ -545,8 +536,6 @@ func (w *ServerInterfaceWrapper) ListThings(ctx echo.Context) error { func (w *ServerInterfaceWrapper) AddThing(ctx echo.Context) error { var err error - ctx.Set(string(BearerAuthScopes), []string{"things:w"}) - // Invoke the callback with all the unmarshaled arguments err = w.Handler.AddThing(ctx) return err diff --git a/examples/authenticated-api/stdhttp/api/api.gen.go b/examples/authenticated-api/stdhttp/api/api.gen.go index 3230ce0c15..b31f3977b1 100644 --- a/examples/authenticated-api/stdhttp/api/api.gen.go +++ b/examples/authenticated-api/stdhttp/api/api.gen.go @@ -21,10 +21,6 @@ import ( "github.com/getkin/kin-openapi/openapi3" ) -const ( - BearerAuthScopes bearerAuthContextKey = "BearerAuth.Scopes" -) - // Error defines model for Error. type Error struct { // Code Error code @@ -45,9 +41,6 @@ type ThingWithID struct { Name string `json:"name"` } -// bearerAuthContextKey is the context key for BearerAuth security scheme -type bearerAuthContextKey string - // AddThingJSONRequestBody defines body for AddThing for application/json ContentType. type AddThingJSONRequestBody = Thing @@ -538,12 +531,6 @@ type MiddlewareFunc func(http.Handler) http.Handler // ListThings operation middleware func (siw *ServerInterfaceWrapper) ListThings(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - - ctx = context.WithValue(ctx, BearerAuthScopes, []string{}) - - r = r.WithContext(ctx) - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.ListThings(w, r) })) @@ -558,12 +545,6 @@ func (siw *ServerInterfaceWrapper) ListThings(w http.ResponseWriter, r *http.Req // AddThing operation middleware func (siw *ServerInterfaceWrapper) AddThing(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - - ctx = context.WithValue(ctx, BearerAuthScopes, []string{"things:w"}) - - r = r.WithContext(ctx) - handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { siw.Handler.AddThing(w, r) })) diff --git a/internal/test/aggregates/anyof/anyof.gen.go b/internal/test/aggregates/anyof/anyof.gen.go index 696441e2e0..bd40bd8187 100644 --- a/internal/test/aggregates/anyof/anyof.gen.go +++ b/internal/test/aggregates/anyof/anyof.gen.go @@ -16,10 +16,6 @@ import ( "github.com/oapi-codegen/runtime" ) -const ( - ApiKeyAuthScopes apiKeyAuthContextKey = "ApiKeyAuth.Scopes" -) - // Defines values for Issue1189TestFieldA1. const ( Issue1189TestFieldA1Bar Issue1189TestFieldA1 = "bar" @@ -196,9 +192,6 @@ type RefRat struct { Squeaks *bool `json:"squeaks,omitempty"` } -// apiKeyAuthContextKey is the context key for ApiKeyAuth security scheme -type apiKeyAuthContextKey string - // GetInlinePets200JSONResponseBody_Data_Item defines parameters for GetInlinePets. type GetInlinePets200JSONResponseBody_Data_Item struct { union json.RawMessage @@ -1343,8 +1336,6 @@ type ServerInterfaceWrapper struct { func (w *ServerInterfaceWrapper) GetInlinePets(ctx echo.Context) error { var err error - ctx.Set(string(ApiKeyAuthScopes), []string{}) - // Invoke the callback with all the unmarshaled arguments err = w.Handler.GetInlinePets(ctx) return err @@ -1354,8 +1345,6 @@ func (w *ServerInterfaceWrapper) GetInlinePets(ctx echo.Context) error { func (w *ServerInterfaceWrapper) GetIssue1189Test(ctx echo.Context) error { var err error - ctx.Set(string(ApiKeyAuthScopes), []string{}) - // Invoke the callback with all the unmarshaled arguments err = w.Handler.GetIssue1189Test(ctx) return err @@ -1365,8 +1354,6 @@ func (w *ServerInterfaceWrapper) GetIssue1189Test(ctx echo.Context) error { func (w *ServerInterfaceWrapper) GetParamTest(ctx echo.Context) error { var err error - ctx.Set(string(ApiKeyAuthScopes), []string{}) - // Parameter object where we will unmarshal all parameters from the context var params GetParamTestParams // ------------- Optional query parameter "test" ------------- @@ -1392,8 +1379,6 @@ func (w *ServerInterfaceWrapper) GetParamTest(ctx echo.Context) error { func (w *ServerInterfaceWrapper) GetRefPets(ctx echo.Context) error { var err error - ctx.Set(string(ApiKeyAuthScopes), []string{}) - // Invoke the callback with all the unmarshaled arguments err = w.Handler.GetRefPets(ctx) return err diff --git a/internal/test/clients/clients.gen.go b/internal/test/clients/clients.gen.go index 7343561245..dc64951324 100644 --- a/internal/test/clients/clients.gen.go +++ b/internal/test/clients/clients.gen.go @@ -14,19 +14,12 @@ import ( "strings" ) -const ( - OpenIdScopes openIdContextKey = "OpenId.Scopes" -) - // SchemaObject defines model for SchemaObject. type SchemaObject struct { FirstName string `json:"firstName"` Role string `json:"role"` } -// openIdContextKey is the context key for OpenId security scheme -type openIdContextKey string - // PostVendorJsonApplicationVndAPIPlusJSONBody defines parameters for PostVendorJson. type PostVendorJsonApplicationVndAPIPlusJSONBody = map[string]interface{} diff --git a/internal/test/naming/identifiers/identifiers_schemas.gen.go b/internal/test/naming/identifiers/identifiers_schemas.gen.go index c88243f327..325303f80d 100644 --- a/internal/test/naming/identifiers/identifiers_schemas.gen.go +++ b/internal/test/naming/identifiers/identifiers_schemas.gen.go @@ -20,19 +20,12 @@ import ( "github.com/oapi-codegen/runtime" ) -const ( - Access_tokenScopes accessTokenContextKey = "access_token.Scopes" -) - // N5StartsWithNumber This schema name starts with a number type N5StartsWithNumber = map[string]interface{} // StringInPath defines model for StringInPath. type StringInPath = string -// accessTokenContextKey is the context key for access-token security scheme -type accessTokenContextKey string - // RequestEditorFn is the function signature for the RequestEditor callback function type RequestEditorFn func(ctx context.Context, req *http.Request) error @@ -546,8 +539,6 @@ func (w *ServerInterfaceWrapper) Issue209(ctx echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter str: %s", err)) } - ctx.Set(string(Access_tokenScopes), []string{}) - // Invoke the callback with all the unmarshaled arguments err = w.Handler.Issue209(ctx, str) return err @@ -564,8 +555,6 @@ func (w *ServerInterfaceWrapper) Issue30(ctx echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter fallthrough: %s", err)) } - ctx.Set(string(Access_tokenScopes), []string{}) - // Invoke the callback with all the unmarshaled arguments err = w.Handler.Issue30(ctx, pFallthrough) return err @@ -582,8 +571,6 @@ func (w *ServerInterfaceWrapper) Issue41(ctx echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter 1param: %s", err)) } - ctx.Set(string(Access_tokenScopes), []string{}) - // Invoke the callback with all the unmarshaled arguments err = w.Handler.Issue41(ctx, n1param) return err diff --git a/internal/test/references/multipackage/petstore/petstore.gen.go b/internal/test/references/multipackage/petstore/petstore.gen.go index b0a1560b28..c90418f824 100644 --- a/internal/test/references/multipackage/petstore/petstore.gen.go +++ b/internal/test/references/multipackage/petstore/petstore.gen.go @@ -16,11 +16,6 @@ import ( "github.com/getkin/kin-openapi/openapi3" ) -const ( - Api_keyScopes apiKeyContextKey = "api_key.Scopes" - Petstore_authScopes petstoreAuthContextKey = "petstore_auth.Scopes" -) - // Defines values for OrderStatus. const ( Approved OrderStatus = "approved" @@ -208,12 +203,6 @@ type User struct { // UserArray defines model for UserArray. type UserArray = []User -// apiKeyContextKey is the context key for api_key security scheme -type apiKeyContextKey string - -// petstoreAuthContextKey is the context key for petstore_auth security scheme -type petstoreAuthContextKey string - // FindPetsByStatusParams defines parameters for FindPetsByStatus. type FindPetsByStatusParams struct { // Status Status values that need to be considered for filter diff --git a/internal/test/references/multipackage/pruned_deps/api.gen.go b/internal/test/references/multipackage/pruned_deps/api.gen.go index f7ef6cc852..ac4d6002cf 100644 --- a/internal/test/references/multipackage/pruned_deps/api.gen.go +++ b/internal/test/references/multipackage/pruned_deps/api.gen.go @@ -33,9 +33,6 @@ type N404 = externalRef0.Error // ThingResponse Object containing list of Things type ThingResponse = ThingList -// bearerAuthWebhookContextKey is the context key for bearerAuthWebhook security scheme -type bearerAuthWebhookContextKey string - // RequestEditorFn is the function signature for the RequestEditor callback function type RequestEditorFn func(ctx context.Context, req *http.Request) error diff --git a/internal/test/servers/middleware/fiber/config.yaml b/internal/test/servers/middleware/fiber/config.yaml index f1c96093a2..66a0846f00 100644 --- a/internal/test/servers/middleware/fiber/config.yaml +++ b/internal/test/servers/middleware/fiber/config.yaml @@ -3,4 +3,9 @@ package: serversmiddlewarefiber generate: fiber-server: true models: true +# Opt into the deprecated scope-emission behavior so the issue-518 regression +# stays meaningful: even with scopes enabled, an operation with an anonymous +# `{}` security alternative must not embed scopes into the request context. +compatibility: + enable-auth-scopes-on-context: true output: middleware.gen.go diff --git a/pkg/codegen/codegen.go b/pkg/codegen/codegen.go index e87142dcfc..d365652f97 100644 --- a/pkg/codegen/codegen.go +++ b/pkg/codegen/codegen.go @@ -926,9 +926,12 @@ func collectComponentTypes(t *template.Template, swagger *openapi3.T, excludeSch if err != nil { return nil, fmt.Errorf("error generating Go types for component request bodies: %w", err) } - securitySchemeTypes, err := GenerateTypesForSecuritySchemes(t, swagger.Components.SecuritySchemes) - if err != nil { - return nil, fmt.Errorf("error generating Go types for component security schemes: %w", err) + var securitySchemeTypes []TypeDefinition + if globalState.options.Compatibility.EnableAuthScopesOnContext { + securitySchemeTypes, err = GenerateTypesForSecuritySchemes(t, swagger.Components.SecuritySchemes) + if err != nil { + return nil, fmt.Errorf("error generating Go types for component security schemes: %w", err) + } } allTypes := append(schemaTypes, paramTypes...) allTypes = append(allTypes, responseTypes...) diff --git a/pkg/codegen/codegen_test.go b/pkg/codegen/codegen_test.go index 600aaf308d..0e873cbe49 100644 --- a/pkg/codegen/codegen_test.go +++ b/pkg/codegen/codegen_test.go @@ -461,5 +461,58 @@ components: } } +// TestEnableAuthScopesOnContext verifies that generated server code embeds +// security scheme scopes into the request context only when the deprecated +// enable-auth-scopes-on-context compatibility option is set. +// Please see https://github.com/oapi-codegen/oapi-codegen/issues/1524 +func TestEnableAuthScopesOnContext(t *testing.T) { + const spec = ` +openapi: "3.0.0" +info: + version: 1.0.0 + title: Test Auth Scopes Emission +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer +paths: + /secured: + get: + operationId: secured + security: + - bearerAuth: ["read"] + responses: + '200': + description: ok +` + loader := openapi3.NewLoader() + swagger, err := loader.LoadFromData([]byte(spec)) + require.NoError(t, err) + + opts := Configuration{ + PackageName: "api", + Generate: GenerateOptions{ + StdHTTPServer: true, + Models: true, + }, + } + + // By default, no context key types, scope constants, or context values + // are generated. + code, err := Generate(swagger, opts) + require.NoError(t, err) + assert.NotContains(t, code, "BearerAuthScopes") + assert.NotContains(t, code, "bearerAuthContextKey") + assert.NotContains(t, code, "context.WithValue") + + // With the compatibility option set, the legacy scope emission returns. + opts.Compatibility.EnableAuthScopesOnContext = true + code, err = Generate(swagger, opts) + require.NoError(t, err) + assert.Contains(t, code, `BearerAuthScopes bearerAuthContextKey = "bearerAuth.Scopes"`) + assert.Contains(t, code, `ctx = context.WithValue(ctx, BearerAuthScopes, []string{"read"})`) +} + //go:embed test_spec.yaml var testOpenAPIDefinition string diff --git a/pkg/codegen/configuration.go b/pkg/codegen/configuration.go index 5048c26af6..f439d82b47 100644 --- a/pkg/codegen/configuration.go +++ b/pkg/codegen/configuration.go @@ -345,6 +345,20 @@ type CompatibilityOptions struct { // are treated as required. // Please see https://github.com/oapi-codegen/oapi-codegen/issues/2267 HeadersImplicitlyRequired bool `yaml:"headers-implicitly-required,omitempty"` + + // EnableAuthScopesOnContext re-enables the legacy emission of security + // scheme scopes by generated server code: the per-scheme context key + // types (e.g. `bearerAuthContextKey`), the scope constants (e.g. + // `BearerAuthScopes`), and the per-operation calls that store the + // operation's scopes into the request context. + // This mechanism is deprecated and off by default: it flattens the + // OpenAPI `security` requirements into a per-scheme list of scopes, and + // cannot represent alternative schemes (OR), combined schemes (AND), or + // anonymous (`{}`) alternatives. Authentication and authorization should + // instead be performed at runtime using the request validation + // middleware, which evaluates the spec's security requirements directly. + // Please see https://github.com/oapi-codegen/oapi-codegen/issues/1524 + EnableAuthScopesOnContext bool `yaml:"enable-auth-scopes-on-context,omitempty"` } func (co CompatibilityOptions) Validate() map[string]string { diff --git a/pkg/codegen/templates/chi/chi-middleware.tmpl b/pkg/codegen/templates/chi/chi-middleware.tmpl index 08402e2aca..b8392427f9 100644 --- a/pkg/codegen/templates/chi/chi-middleware.tmpl +++ b/pkg/codegen/templates/chi/chi-middleware.tmpl @@ -39,7 +39,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(w http.ResponseWriter, r *http.Requ {{end}} - {{if .SecurityDefinitions -}} + {{if and .SecurityDefinitions opts.Compatibility.EnableAuthScopesOnContext -}} ctx := r.Context() {{range .SecurityDefinitions}} ctx = context.WithValue(ctx, {{.ProviderName | sanitizeGoIdentity | ucFirst}}Scopes, {{toStringArray .Scopes}}) diff --git a/pkg/codegen/templates/constants.tmpl b/pkg/codegen/templates/constants.tmpl index 2af795c97b..4d451ae337 100644 --- a/pkg/codegen/templates/constants.tmpl +++ b/pkg/codegen/templates/constants.tmpl @@ -1,4 +1,4 @@ -{{- if gt (len .SecuritySchemeProviderNames) 0 }} +{{- if and (gt (len .SecuritySchemeProviderNames) 0) opts.Compatibility.EnableAuthScopesOnContext }} const ( {{range $ProviderName := .SecuritySchemeProviderNames}} {{- $ProviderName | sanitizeGoIdentity | ucFirst}}Scopes {{$ProviderName | schemaNameToTypeName | lcFirst}}ContextKey = "{{$ProviderName}}.Scopes" diff --git a/pkg/codegen/templates/echo/echo-wrappers.tmpl b/pkg/codegen/templates/echo/echo-wrappers.tmpl index 064bd7f32f..7d19c91d58 100644 --- a/pkg/codegen/templates/echo/echo-wrappers.tmpl +++ b/pkg/codegen/templates/echo/echo-wrappers.tmpl @@ -25,9 +25,11 @@ func (w *ServerInterfaceWrapper) {{.OperationId}} (ctx echo.Context) error { {{end}} {{end}} +{{if opts.Compatibility.EnableAuthScopesOnContext -}} {{range .SecurityDefinitions}} ctx.Set(string({{.ProviderName | sanitizeGoIdentity | ucFirst}}Scopes), {{toStringArray .Scopes}}) {{end}} +{{- end}} {{if .RequiresParamObject}} // Parameter object where we will unmarshal all parameters from the context diff --git a/pkg/codegen/templates/echo/v5/echo-wrappers.tmpl b/pkg/codegen/templates/echo/v5/echo-wrappers.tmpl index 0477ddcd34..8fcab2c66c 100644 --- a/pkg/codegen/templates/echo/v5/echo-wrappers.tmpl +++ b/pkg/codegen/templates/echo/v5/echo-wrappers.tmpl @@ -25,9 +25,11 @@ func (w *ServerInterfaceWrapper) {{.OperationId}} (ctx *echo.Context) error { {{end}} {{end}} +{{if opts.Compatibility.EnableAuthScopesOnContext -}} {{range .SecurityDefinitions}} ctx.Set(string({{.ProviderName | sanitizeGoIdentity | ucFirst}}Scopes), {{toStringArray .Scopes}}) {{end}} +{{- end}} {{if .RequiresParamObject}} // Parameter object where we will unmarshal all parameters from the context diff --git a/pkg/codegen/templates/fiber/fiber-middleware.tmpl b/pkg/codegen/templates/fiber/fiber-middleware.tmpl index ce20c29a4d..9af1e2a93e 100644 --- a/pkg/codegen/templates/fiber/fiber-middleware.tmpl +++ b/pkg/codegen/templates/fiber/fiber-middleware.tmpl @@ -47,9 +47,11 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *fiber.Ctx) error { {{end}} +{{if opts.Compatibility.EnableAuthScopesOnContext -}} {{range .SecurityDefinitions}} c.Context().SetUserValue(({{.ProviderName | sanitizeGoIdentity | ucFirst}}Scopes), {{toStringArray .Scopes}}) {{end}} +{{- end}} {{if .RequiresParamObject}} // Parameter object where we will unmarshal all parameters from the context diff --git a/pkg/codegen/templates/gin/gin-wrappers.tmpl b/pkg/codegen/templates/gin/gin-wrappers.tmpl index 87f16a56f8..b768c67a95 100644 --- a/pkg/codegen/templates/gin/gin-wrappers.tmpl +++ b/pkg/codegen/templates/gin/gin-wrappers.tmpl @@ -40,9 +40,11 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *gin.Context) { {{end}} +{{if opts.Compatibility.EnableAuthScopesOnContext -}} {{range .SecurityDefinitions}} c.Set(string({{.ProviderName | sanitizeGoIdentity | ucFirst}}Scopes), {{toStringArray .Scopes}}) {{end}} +{{- end}} {{if .RequiresParamObject}} // Parameter object where we will unmarshal all parameters from the context diff --git a/pkg/codegen/templates/gorilla/gorilla-middleware.tmpl b/pkg/codegen/templates/gorilla/gorilla-middleware.tmpl index c971395fb8..2ef4b852e1 100644 --- a/pkg/codegen/templates/gorilla/gorilla-middleware.tmpl +++ b/pkg/codegen/templates/gorilla/gorilla-middleware.tmpl @@ -39,7 +39,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(w http.ResponseWriter, r *http.Requ {{end}} - {{if .SecurityDefinitions -}} + {{if and .SecurityDefinitions opts.Compatibility.EnableAuthScopesOnContext -}} ctx := r.Context() {{range .SecurityDefinitions}} ctx = context.WithValue(ctx, {{.ProviderName | sanitizeGoIdentity | ucFirst}}Scopes, {{toStringArray .Scopes}}) diff --git a/pkg/codegen/templates/iris/iris-middleware.tmpl b/pkg/codegen/templates/iris/iris-middleware.tmpl index 769f2331bc..46eddccaa2 100644 --- a/pkg/codegen/templates/iris/iris-middleware.tmpl +++ b/pkg/codegen/templates/iris/iris-middleware.tmpl @@ -35,9 +35,11 @@ func (w *ServerInterfaceWrapper) {{.OperationId}} (ctx iris.Context) { {{end}} {{end}} +{{if opts.Compatibility.EnableAuthScopesOnContext -}} {{range .SecurityDefinitions}} ctx.Set(string({{.ProviderName | sanitizeGoIdentity | ucFirst}}Scopes), {{toStringArray .Scopes}}) {{end}} +{{- end}} {{if .RequiresParamObject}} // Parameter object where we will unmarshal all parameters from the context diff --git a/pkg/codegen/templates/stdhttp/std-http-middleware.tmpl b/pkg/codegen/templates/stdhttp/std-http-middleware.tmpl index 8058ed1714..65c62cacb0 100644 --- a/pkg/codegen/templates/stdhttp/std-http-middleware.tmpl +++ b/pkg/codegen/templates/stdhttp/std-http-middleware.tmpl @@ -39,7 +39,7 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(w http.ResponseWriter, r *http.Requ {{end}} - {{if .SecurityDefinitions -}} + {{if and .SecurityDefinitions opts.Compatibility.EnableAuthScopesOnContext -}} ctx := r.Context() {{range .SecurityDefinitions}} ctx = context.WithValue(ctx, {{.ProviderName | sanitizeGoIdentity | ucFirst}}Scopes, {{toStringArray .Scopes}})