Search code examples
swaggeropenapiswagger-ui

Is it allowed to specify the same authentication method several times in OpenAPI?


I have a web application that requires a login. You can log in by entering your username and password and you will receive a JSON Web Token. The JWT is sent in the Authorization header with every HTTP request to a URL that requires authentication: Authorization: Bearer JWT. There are three ways to define that in OpenAPI:

components:
  securitySchemes:
    api_key:
      type: apiKey
      name: Authorization
      in: header
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
components:
  securitySchemes:
    oAuth2Password:
      type: oauth2
      flows: 
        password: 
          tokenUrl: https://example.com/api/oauth2/token
          scopes: {}

All of them specify that you need to pass a token in the Authorization header. But OAuth2 Password flow is the most complete and informative description. Can I use multiple redundant descriptions for the same authentication method?

Why define multiple security schemes in OpenAPI?

I cannot sign in with Swagger UI using the OAuth2 Password flow. Different parts of my application run on separate web server instances. Sometimes the login server isn't running while I'm testing another part of my application. In that case I cannot sign in with Swagger UI.
I could create a JWT manually and use it in Swagger UI if I defined http bearer authentication or apiKey authentication. But with OAuth2 Password flow Swagger UI trys to reach the login server (defined in tokenUrl) and fails. It doesn't let me enter a token manually.
That's why I want to define OAuth2 Password flow and http bearer authentication in OpenAPI describing the same authentication method two times in two different ways. Is it good practice to use multiple redundant descriptions for the same authentication method in OpenAPI? (All three security schemas describe the same authentication method of my application. The only difference is that Swagger UI handles them differently.)

Duplicate?

Swagger - Adding multiple security parameters to the same schema definition
Using an API Key & Secret for Swagger Security Scheme

Both questions ask about adding multiple OpenAPI security schemes for different HTTP headers they want to use. I want to know if it's okay to add multiple (redundant) security schemes for the same header (for the Authorization header).


Solution

  • Yes, it's valid to declare multiple security schemes. OpenAPI doesn't care that they're actually the same thing described differently.

    Take care that if you add a scheme for local testing, you don't accidentally deploy it to production where it either isn't valid or shouldn't be. One option is to add the extra scheme using an overlay or decorator, only for testing purposes, rather than editing the main OpenAPI description.