Authentication

OAuth2 API Security and JWT Authentication

Select the right flow, validate tokens at the API boundary, and document security requirements in OpenAPI.

Published: 19 September 2026 · APISAST

Updated: 19 September 2026

Separate OAuth2 from JWT

OAuth2 API security depends on how a client obtains and uses an access token. JWT is one possible token format; an OAuth2 server can also issue opaque tokens. Neither format grants permission by itself. The resource server must validate the token and decide whether its scopes and claims allow the requested action.

For a browser or mobile client acting for a user, use authorization code with PKCE. For a service acting on its own behalf, use client credentials with a narrowly scoped identity. Avoid putting access tokens in query strings, where URLs may appear in logs or browser history.

Validate every access token

  • Verify the signature with trusted keys and allow only the algorithms your issuer uses. Reject unsigned or unexpected algorithms.
  • Check issuer, audience, expiry, and any relevant not-before value. Allow only limited clock skew.
  • Use the token’s subject and scopes to make a separate authorization decision for the specific resource.
  • Rotate signing keys safely. Keep access tokens short lived and protect refresh tokens with secure storage and rotation.

A valid token for one customer must not open another customer’s object. Test object-level authorization with two identities and realistic resource IDs. Zero trust API design covers this per-request check in more detail.

Describe authentication in OpenAPI

Define an OAuth2 security scheme with the actual authorization and token URLs for your provider, then list the scopes each operation needs. Apply a global requirement if most operations are private; mark genuinely public routes explicitly. If your API accepts a bearer JWT without an OAuth2 flow, use an HTTP bearer scheme. Keep examples free of real credentials.

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerAuth: []

The bearerFormat hint documents a format; it does not force the server to validate JWTs. For OAuth2, describe flows and scopes instead of treating the bearer example as a substitute for the authorization server configuration.

Design the flow around the client

A browser application cannot keep a client secret confidential, so an authorization-code flow with PKCE is a better fit than treating the browser as a trusted server. Register redirect URIs precisely and validate the issuer that returned the authorization response. A backend service without a user can request a token with client credentials, but that token should represent the service and carry only the permissions it needs. Avoid using a powerful service token as a shortcut for every user request.

Describe these choices in your architecture notes and OpenAPI security schemes. The contract should show which operations require a bearer token and, for OAuth2 flows, which scopes apply. A security declaration tells clients what to send; only the resource server can enforce it. Follow the current OAuth2 security best current practice when choosing redirect-based flow controls.

Keep token validation separate from permissions

Signature verification answers whether a trusted issuer signed a JWT. It does not answer whether this caller may edit a particular invoice. After checking issuer, audience, expiry, and signature, map the subject to an application identity and make an authorization decision using the resource's owner and the requested action. This separation is especially important for multi-tenant APIs: a valid token for tenant A must never unlock tenant B's records.

Use short-lived access tokens and a documented refresh process. An opaque access token may need introspection rather than local JWT validation; the API must know which format its authorization server issues. Cache validation results carefully so a revoked token does not remain usable longer than policy allows. Never log the full Authorization header or put a bearer token in a URL, even in a troubleshooting example.

Plan failure responses and recovery

Return 401 when authentication is absent or invalid, and 403 when an authenticated caller lacks permission. Keep the body useful without exposing token contents, signatures, or internal policy details. A client can often renew a short-lived token after a 401, but blindly retrying a 403 will not create permission. Document both responses on protected operations and test them with missing, expired, wrong-audience, and insufficient-scope tokens.

When a signing key rotates, publish the new key before switching tokens and keep the old key available only for an appropriate overlap period. Exercise the rotation path in a non-production environment. An OpenAPI scan can flag a missing security requirement, but it cannot detect a bad key rotation, a broken token validator, or a confused-deputy authorization bug.

Review authentication changes in CI

Treat a removed security requirement as a contract change that deserves a human review, especially on write operations. Scan the specification, compare changed endpoints, and run integration tests with at least two identities and two resource owners. A regression test should demonstrate that a valid token cannot cross tenant boundaries and that an anonymous caller cannot use a protected operation. This creates evidence about actual behaviour, while the static scan provides evidence about the documented design.

Include a test for a token issued to a different audience. It may have a valid signature yet still be invalid for this API. Record the expected 401 or 403 result so a future auth-library upgrade cannot silently loosen the boundary.

What a static scan can check

APISAST can flag missing security schemes, operations without declared security requirements, and API keys placed in query parameters. Its API SAST checks read the specification; they do not validate a live token, inspect your authorization server, or prove that a scope is enforced. Follow a clean contract scan with authentication and authorization integration tests.

Review the OpenAPI scanner workflow before uploading the updated specification.

More API security guides