oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Get security scopes from context

Open corani opened this issue 3 years ago • 0 comments

In my project I'm using a sidecar that handles authentication and injects a header into the request containing the scopes for which the user is authorized.

In the application itself I annotate the different endpoints with the required scopes and match these via a middleware function with the scopes from the user request.

I found myself repeating the code to get the security scopes from the context in multiple places. This change generates a simple getter for this that handles the type cast.

Usage:

paths:
  /public/resource:
    get:
  /private/resource:
    get:
      security:
        - AuthInfo: ["read"]
    post:
      security:
        - AuthInfo: ["write"]
components:
  securitySchemes:
    AuthInfo:
      type: apiKey
      in: header
      name: X-Authinfo
apiScopes := openapi3.AuthInfoScopesFromContext(req.Context())

if scopes == nil {
    // no authorization needed
} else {
    // match apiScopes with request scopes
}

corani avatar Jul 18 '22 06:07 corani