JWT Bearer Token Authentication in OpenAPI

Define JWT Bearer token authentication in OpenAPI 3.0 using securitySchemes. Learn how to apply security requirements globally or per-endpoint with the bearer scheme and JWT format.

Authentication

Detailed Explanation

JWT Bearer Authentication in OpenAPI

JSON Web Token (JWT) authentication is the most common security scheme for modern REST APIs. OpenAPI provides a structured way to document bearer token authentication so that clients and tools like Swagger UI can understand and test authenticated endpoints.

Defining the Security Scheme

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        JWT token obtained from /auth/login.
        Include in Authorization header as: Bearer <token>

The bearerFormat: JWT is a hint for documentation tools — it does not enforce JWT validation. The actual token validation happens server-side.

Applying Security Globally

To require authentication on all endpoints by default:

security:
  - bearerAuth: []

This top-level security block means every endpoint requires the bearer token unless overridden.

Per-Endpoint Security

Override or remove security on specific endpoints:

paths:
  /auth/login:
    post:
      security: []   # No auth required
      summary: Login and get token

  /users/me:
    get:
      security:
        - bearerAuth: []
      summary: Get current user profile

Setting security: [] (empty array) on login and registration endpoints exempts them from authentication.

Multiple Auth Methods

Support both API key and JWT:

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key

# Either method works (OR logic)
security:
  - bearerAuth: []
  - apiKey: []

When multiple schemes are listed at the same level, they use OR logic — the client can use either method.

OAuth2 Scopes with JWT

For fine-grained permissions:

components:
  securitySchemes:
    oauth2:
      type: oauth2
      flows:
        implicit:
          authorizationUrl: https://auth.example.com/authorize
          scopes:
            read:users: Read user information
            write:users: Modify user information

paths:
  /users:
    get:
      security:
        - oauth2: [read:users]

This documents that the endpoint requires specific OAuth2 scopes, which maps naturally to JWT claims in practice.

Use Case

JWT authentication documentation is essential for any API that requires user authentication. Frontend developers, mobile app teams, and third-party integrators all rely on the security scheme definition to understand how to authenticate requests. Swagger UI uses this definition to add an 'Authorize' button that lets testers input their JWT token for interactive testing.

Try It — OpenAPI Editor & Viewer

Open full tool