GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Provide first-class (generated) code to support authentication/authorization · Issue #1524 · oapi-codegen/oapi-codegen

Provide first-class (generated) code to support authentication/authorization #1524

New issue
Copy link
New issue
Copy link
Closed as not planned
Closed as not planned
Provide first-class (generated) code to support authentication/authorization#1524
Copy link
Labels
enhancementNew feature or requestNew feature or request

Description

@jamietanna
jamietanna
opened on Mar 29, 2024
Issue body actions

As part of #1254 I'm looking at documenting the way that securitySchemes works, and it turns out it's a little more lackluster than I remember.

Right now, if you define an endpoint i.e.:

  /apiKey:
    get:
      operationId: apiKey
      description: Perform an authenticated request, using an API Key in the `X-API-Key` header
      security:
        - apiKey: []
      responses:
      # ... snip 

This generates only the following code:

@@ -20,7 +20,6 @@ import (
 )
 
 const (
+       ApiKeyScopes    = "apiKey.Scopes"
        BasicAuthScopes = "basicAuth.Scopes"
 )
 
@@ -55,8 +54,6 @@ type MiddlewareFunc func(http.Handler) http.Handler
 func (siw *ServerInterfaceWrapper) ApiKey(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()
 
+       ctx = context.WithValue(ctx, ApiKeyScopes, []string{})
+
        handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                siw.Handler.ApiKey(w, r)
        }))

This still requires a lot of work to hand-roll server-side authentication.

We should instead generate

We can generated ??, and then rely on an implemented method sfor

multi reoutes

k
Although it can be possible to use the middleware to authenticate, I believe it's an area we can improve on.

We'll need to consider:

  • the existence of the middleware(s) to not re-authenticate
  • the existence of multiple means to authenticate - is it first one wins?

This should be opt-in.

Example schema:

Some code can be found in 09adbb0

See also:

#843
#177
#221
#911

Reacted by esprimo, Thore Göbel and Borhan Hafez
Reacted by Khadim Fall, Jordi Burgos, Lâm Hoàng Phúc, markpsiano and esprimo

Activity

  1. jamietanna
    added
    enhancementNew feature or requestNew feature or request
    on Mar 29, 2024
  2. alehed commented on Jun 6, 2024

    @alehed
    alehed
    on Jun 6, 2024
    More actions

    The current approach sort of works if you restrict yourself to one security scheme per endpoint. We are currently using a middleware which checks the request against the given authenticators. Using it looks something like this:

    serverOptions := demo.ChiServerOptions{
    	...
    	Middlewares: []demo.MiddlewareFunc{
    		OAPICodegenAuthMiddleware(map[string]Authenticator{
    			api.ApiKeyScopes:    ApiKeyAuthenticator(db),
    			api.BasicAuthScopes: BasicAuthenticator(usernamePasswordHashes),
    		})},
    }
  3. alehed commented on Jun 6, 2024

    @alehed
    alehed
    on Jun 6, 2024
    More actions

    For the issue with multiple security schemes per endpoint see #1644.

    Our middleware currently resolves this problem by always assuming OR (which is the more common case) and disallowing AND-ing security schemes, but that has other drawbacks.

  4. mromaszewicz commented on Jun 6, 2024

    @mromaszewicz
    mromaszewicz
    on Jun 6, 2024
    Member
    More actions

    IMO, putting anything to do with auth scopes into the generated code was a mistake, because it's a runtime behavior handled properly by openapi3filter. I have an API running at my workplace which has a complex specification with multiple schemes and it works ok.

    I think we should deprecate authentication logic from the generated code altogether, and I'm happy to clean up the middleware or example to make it clear how to do this. Our middleware was written when openapi3filter was quite more primitive, and we could use it better today.

  5. juan-carvajal commented on Aug 4, 2025

    @juan-carvajal
    juan-carvajal
    on Aug 4, 2025
    More actions

    What is the recommended way of getting the user context from a bearer token if using strict server? Should we just add the Authorization header as a required property in the models of each request?

  6. juan-carvajal commented on Aug 4, 2025

    @juan-carvajal
    juan-carvajal
    on Aug 4, 2025
    More actions

    What is the recommended way of getting the user context from a bearer token if using strict server? Should we just add the Authorization header as a required property in the models of each request?

    Just asking because in the strict handlers, there is no access to the raw request, so no way to get the header information...I guess you could always store the token info in the context via middleware (not ideal), but this feels like a missing feature especially when talking about JWT tokens which identify API consumers are can affect the request outcome.

  7. juan-carvajal commented on Aug 4, 2025

    @juan-carvajal
    juan-carvajal
    on Aug 4, 2025
    More actions

    What is the recommended way of getting the user context from a bearer token if using strict server? Should we just add the Authorization header as a required property in the models of each request?

    Just asking because in the strict handlers, there is no access to the raw request, so no way to get the header information...I guess you could always store the token info in the context via middleware (not ideal), but this feels like a missing feature especially when talking about JWT tokens which identify API consumers are can affect the request outcome.

    Sorry, I am talking about the Golang server implementation, e.g:

    func (h HTTPServer) GetModelGroups(ctx context.Context, request GetModelGroupsRequestObject) (GetModelGroupsResponseObject, error) {
    	// TODO implement me
    	r, err := h.application.Queries.GetModelGroups.Handle(ctx, query.GetModelGroups{
    		User: acl.NewUser("", "", request.Params.PartitionId), // HOW TO GET JWT TOKEN HERE
    	})
    	if err != nil {
    		return GetModelGroupsdefaultJSONResponse{
    			Body:       ProblemDetails{},
    			StatusCode: 0,
    		}, nil
    	}
    	return GetModelGroups200JSONResponse{
    		{
    			Acl:         nil,
    			Data:        r[0].Data,
    			Description: r[0].Description,
    			Id:          r[0].ID,
    			Legal:       nil,
    			Name:        r[0].Name,
    		},
    	}, nil
    }
  8. mromaszewicz commented on Feb 7, 2026

    @mromaszewicz
    mromaszewicz
    on Feb 7, 2026
    Member
    More actions

    Auth should be handled at runtime via openapi3filter, not generated code. The existing scopes constants in generated code were a design misstep and shouldn't be expanded further.

  9. mromaszewicz
    closed this as not plannedon Feb 7, 2026
  10. mromaszewicz
    added a commit that references this issue on Jul 7, 2026

    Deprecate ctx based security scopes (#2440)

    41eeb46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402503 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.