Authorization bearer token in openapi and its usage
Using 'Authorization: Bearer <token>' in an OpenAPI (Swagger) specification requires defining a security scheme and then applying it to the relevant API endpoints. The method for doing this varies slightly between OpenAPI versions 2.0, 3.0, and 3.1.
OpenAPI 3.0 and 3.1
In OpenAPI 3.0 and 3.1, the process is straightforward using the bearerAuth
security scheme. This is the most modern and recommended way to specify Bearer token authentication.
First, define the security scheme in the components
section of your specification:
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
type: http
: Specifies that the scheme uses standard HTTP authentication headers.scheme: bearer
: Designates the authentication type asBearer
.bearerFormat: JWT
(optional): Provides a hint to client tools that the token is a JSON Web Token.
Once defined, you can apply this security scheme to an entire API or individual endpoints.
Applying to all endpoints:
security:
- bearerAuth: []
Applying to a specific endpoint:
paths:
/users:
get:
summary: Get a list of users
security:
- bearerAuth: []
The empty array []
indicates that no specific scopes are required for this authentication method.
OpenAPI 2.0 (Swagger 2.0)
Swagger 2.0 does not have native support for a bearer
scheme. The common workaround is to use the apiKey
type and specify the header name as Authorization
.
First, define the security definition in the securityDefinitions
section:
securityDefinitions:
apiKeyAuth:
type: apiKey
in: header
name: Authorization
type: apiKey
: The scheme type used for API keys.in: header
: Specifies that the token is passed in a request header.name: Authorization
: The name of the header.
Then, apply the security definition to your API or specific paths:
Applying to all endpoints:
security:
- apiKeyAuth: []
Applying to a specific endpoint:
paths:
/users:
get:
summary: Get a list of users
security:
- apiKeyAuth: []
While this works, it is semantically incorrect as it uses the API key model to represent a Bearer token. This is a hacky solution from the past, as noted in the Stack Overflow answers you linked.
The evolution of the OpenAPI specification from version 2.0 to 3.x shows a clear move toward more explicit and semantically correct security definitions, making it easier for tools to generate correct client code. For any new projects, using OpenAPI 3.0 or 3.1 with the bearerAuth
scheme is the best practice.