Kaiditech

OAuth 2.0 Authorization Framework

OAuth 2.0 Authorization Framework

Introduction

OAuth 2.0 is an authorization framework designed to let applications obtain limited, revocable access to user-owned resources on an HTTP service without sharing user credentials. Instead of handing over a password, users delegate authentication and consent to a trusted authorization server, which issues tokens to client applications. Those tokens carry enough authority for the client to perform specific actions—nothing more, nothing less.

Key Actors

  • Resource Owner: The end user (e.g., Bob) who controls access to protected resources (his orders).
  • Client: A third-party application (e.g., kaiditech) requesting access to the user’s resources.
  • Authorization Server: The service responsible for authenticating the resource owner and issuing authorization codes and tokens.
  • Resource Server: The API hosting the actual protected data (Bob’s order details) and trusting the authorization server’s tokens.

The Authorization Code Flow

This is the most common OAuth 2.0 flow for server-based applications. It involves four main steps:

  1. Authorization Request
    The client redirects the user’s browser to the authorization server’s /authorize endpoint, including:

    • response_type=code (requesting an authorization code)
    • client_id (kaiditech’s public identifier)
    • redirect_uri (callback URL)
    • scope=orders (limited access to order data)
    • state (anti-CSRF token)

    Example Redirect

  2. User Authentication & Consent
    Bob logs into the authorization server. Once authenticated, the server prompts him:
    "kaiditech wants to view your orders—allow?"
    If Bob consents, the server proceeds.

  3. Authorization Response
    Upon consent, the server redirects Bob back to the client’s redirect_uri, appending:

    • code (the authorization code)
    • state (the original anti-CSRF value)

    Example Callback

  4. Token Request
    kaiditech’s backend exchanges the authorization code for an access token by POSTing to /token with:

    • grant_type=authorization_code
    • code (the received code)
    • redirect_uri (must match the original)
    • client_id and client_secret (for authentication)

    Example POST

    Token Response

PKCE (Proof Key for Code Exchange)

PKCE (RFC 7636) enhances the authorization code flow, especially for public clients (e.g., mobile and single-page apps) that cannot safely store a client secret. It prevents interception and replay of the authorization code.

  1. Generate Code Verifier
    The client creates a high-entropy cryptographic random string (the code_verifier), e.g., 43-128 characters.

  2. Compute Code Challenge
    A code_challenge is derived by applying a SHA-256 hash to the code_verifier and base64-url-encoding the result:

  3. Authorization Request with PKCE
    The client sends the code_challenge and code_challenge_method=S256 alongside the standard parameters:

  4. Token Request with Code Verifier
    When exchanging the code, the client includes the original code_verifier:

  5. Server Validation
    The authorization server recalculates the challenge from the supplied code_verifier, compares it with the original code_challenge, and proceeds if they match.

Bonus Security Best Practices

Beyond the core flow and PKCE, consider implementing these additional security measures:

  • Token Revocation Endpoint: Support RFC 7009 to allow clients or users to revoke access and refresh tokens proactively.
  • Refresh Token Rotation: Issue a new refresh token with each access token refresh and invalidate the previous refresh token to mitigate replay attacks.
  • Mutual TLS (mTLS): Require clients to present a valid TLS client certificate when calling token or introspection endpoints.
  • DPoP (Demonstrating Proof of Possession): Bind tokens to a public key via DPoP headers, preventing token replay on different clients.
  • JWT Signature & Claim Validation: Enforce strict validation of JWTs, including issuer (iss), audience (aud), expiration (exp), and JWT ID (jti).
  • Algorithm Restrictions: Only accept tokens signed with strong algorithms (e.g., RS256) and reject none or weak algorithms.
  • CORS and CSP: Configure Cross-Origin Resource Sharing and Content Security Policy headers to restrict where access tokens and API calls can originate.
  • Certificate Pinning: Pin the authorization server’s TLS certificate in public clients to prevent MITM attacks.
  • Rate Limiting and Throttling: Apply rate limits on authentication, token, and resource endpoints to mitigate brute-force and denial-of-service attacks.
  • Detailed Audit Logging: Log authorization requests, token issues, and resource access with enough detail to trace security events.
  • Scope Audience Restriction: Issue and enforce scopes that map precisely to API audiences and operations.
  • Client Secret Rotation: Periodically rotate client credentials and require existing tokens to be reissued under new credentials.
  • Secure Cookie Flags: If using cookies for tokens, set HttpOnly, Secure, and SameSite flags appropriately.
  • HSTS (HTTP Strict Transport Security): Enforce HTTPS by setting HSTS headers with a long max-age and include subdomains.
  • Security Headers: Implement headers like X-Frame-Options, X-Content-Type-Options, and Referrer-Policy.
  • Monitoring & Alerting: Integrate with SIEM or logging platforms to trigger alerts on suspicious activity (e.g., repeated failed grants).

Complete Documentation

Maintain thorough, up-to-date documentation for your OAuth 2.0 implementation:

  • Specification References: Cite relevant RFCs (6749, 6750, 7636, 7009).
  • Flow Diagrams: Include sequence diagrams for each grant type and extension (e.g., PKCE, mTLS).
  • Endpoint Details: Document /authorize, /token, /revoke, and /introspect endpoints with parameters and example requests/responses.
  • Error Codes and Handling: List all OAuth error codes (e.g., invalid_request, invalid_grant, unauthorized_client) and recommended client handling.
  • Security Guidelines: Provide a checklist of required security controls and compliance requirements.
  • Client Integration Guides: Offer sample code and SDK references for popular platforms (Node.js, Java, .NET, iOS, Android).
  • Change Log: Track updates to your OAuth service, token format changes, and deprecation notices.
  • Support and Troubleshooting: Offer a FAQ and guidance for common integration errors, token renewal issues, and scope misconfigurations.

Accessing Protected Resources

With a valid access token in hand, kaiditech makes API calls to the resource server:

The resource server validates the token. If valid, it returns Bob’s orders:

Security Considerations

  1. Use HTTPS Everywhere
  2. Validate Redirect URIs Strictly
  3. Employ the state Parameter
  4. Short-Lived Access Tokens
  5. Scope Minimization
  6. Token Storage and Transmission

Beyond Authorization Code Flow

OAuth 2.0 defines several other grant types for different scenarios:

  • Implicit Flow (discouraged)
  • Resource Owner Password Credentials (first-party only)
  • Client Credentials (server-to-server)
  • Refresh Token (obtain new access tokens)

The authorization code flow with PKCE has become the standard for native and single-page applications.

OAuth 2.0 Bonus Security Checks

Below are detailed explanations for five essential security measures you should implement in addition to the core OAuth 2.0 flows and PKCE:


1. Refresh Token Rotation

Description: Issue a new refresh token each time an access token is refreshed, and immediately invalidate the old refresh token.
Benefits:

  • Limits replay attacks: stolen refresh tokens become single-use.
  • Improves visibility: any reuse of a revoked token can trigger alerts.

Implementation Steps:

  1. Store each refresh token with a unique identifier in your database.
  2. On token refresh:
    • Generate a new refresh token.
    • Overwrite the old token record with the new identifier.
    • Mark the previous token as revoked.
  3. Reject any refresh attempt using an old or already-used token.

2. Token Revocation Endpoint (RFC 7009)

Description: Provide a /revoke endpoint where clients or users can revoke access and refresh tokens.
Benefits:

  • Immediate invalidation of tokens upon user or client request.
  • Essential for lost/stolen device scenarios.

Implementation Steps:

  1. Define a POST /revoke endpoint accepting:
    • token (access or refresh token)
    • client_id and client_secret for authentication.
  2. Lookup the token; if found, mark it revoked and invalidate associated sessions.
  3. Always return HTTP 200 to prevent token enumeration (even if token is unknown).

3. Mutual TLS (mTLS) for Token Endpoints

Description: Require clients to present an X.509 certificate when calling /token, /introspect, or /revoke endpoints.
Benefits:

  • Binds token operations to a specific client certificate.
  • Even if client secrets leak, certificates are required for operations.

Implementation Steps:

  1. Issue each client a unique certificate and private key.
  2. Configure the authorization server to require and validate client certificates on token-related endpoints.
  3. Map client certificates to client records and enforce certificate revocation lists.

4. DPoP (Demonstration of Proof of Possession)

Description: Use DPoP headers to bind access tokens to a public key generated by the client.
Benefits:

  • Prevents token replay on unauthorized clients.
  • Adds an extra layer of proof beyond bearer semantics.

Implementation Steps:

  1. Client generates a public/private key pair per session or key rotation policy.
  2. On each request to /authorize or /token, include a DPoP header:
    • Contains a JWT signed with the private key.
    • Claims include HTTP method, URL, and jti.
  3. Authorization server verifies the DPoP proof and binds the issued token to the DPoP public key.

5. JWT Signature & Claim Validation

Description: Enforce strict validation of JSON Web Tokens (JWTs) used as access tokens.
Benefits:

  • Ensures tokens are legitimate and unaltered.
  • Prevents accepting tokens with weak or missing claims.

Validation Checklist:

  • Signature Algorithm: Only allow strong algorithms (e.g., RS256, ES256).
  • Issuer (iss): Must match your authorization server’s identifier.
  • Audience (aud): Must include your resource server’s identifier.
  • Expiration (exp) & Not Before (nbf): Reject tokens outside valid time window.
  • JWT ID (jti): Check for token reuse or replay.
  • Key Rotation Handling: Fetch and cache JWK Set; handle new keys seamlessly.

Implement these measures collectively to significantly harden your OAuth 2.0 deployment against common attack vectors.

Conclusion

OAuth 2.0 decouples authentication from authorization, giving users granular control over their data and developers a standardized, secure way to access resources. Implement it correctly—strict URI validation, CSRF protections, minimal scopes, short token lifetimes, and use PKCE for public clients—for a robust, scalable authorization layer without compromising user trust.