OpenAPI: JWT Authentication Login Endpoint
Document a JWT-based authentication flow with login, token refresh, and logout endpoints. Includes Bearer token security scheme and token response schemas.
Detailed Explanation
Documenting JWT Authentication in OpenAPI
JWT authentication is the most common pattern for stateless API auth. The OpenAPI specification lets you define both the endpoints and the security scheme.
Security Scheme Definition
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
description: JWT access token obtained from /auth/login
Login Endpoint
paths:
/auth/login:
post:
summary: Authenticate user and obtain JWT
tags:
- Authentication
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- email
- password
properties:
email:
type: string
password:
type: string
responses:
'200':
description: Login successful
content:
application/json:
schema:
$ref: '#/components/schemas/TokenResponse'
'401':
description: Invalid credentials
Token Response Schema
components:
schemas:
TokenResponse:
type: object
required:
- accessToken
- tokenType
- expiresIn
properties:
accessToken:
type: string
description: JWT access token
refreshToken:
type: string
description: Token for obtaining new access tokens
tokenType:
type: string
description: Always "Bearer"
expiresIn:
type: integer
description: Token lifetime in seconds
Token Refresh Endpoint
The refresh endpoint accepts a refresh token and returns a new access token without requiring credentials again. This is essential for mobile apps and SPAs that need to maintain sessions beyond the short access token lifetime (typically 15-30 minutes).
Applying Security Globally
Use the top-level security field to require authentication on all endpoints, then override with an empty array on public endpoints like login and registration.
Use Case
Documenting a backend authentication system where mobile apps, SPAs, or third-party clients need to authenticate via email/password and receive JWT tokens for subsequent API calls.