🔑

Understanding OAuth 2.0 Authorization Code Flow

Feb 10, 2025

Microsoft Identity Platform and OAuth 2.0 Authorization Code Flow

Introduction

  • The OAuth 2.0 authorization code grant type, or auth code flow, allows a client app to access protected resources like web APIs.
  • Requires a user-agent that supports redirection from the authorization server back to the application.
  • Recommended to use Microsoft-supported authentication libraries instead of manually crafting HTTP requests.

Applications Supporting Auth Code Flow

  • Single-page web applications (SPA)
  • Standard web applications
  • Desktop and mobile apps

Protocol Details

  • Based on OAuth 2.0 specification section 4.1.
  • Auth code flow uses an access_token for requests to resources protected by the Microsoft identity platform.
  • Includes a refresh mechanism to request new tokens for previously authenticated entities.

Redirect URIs for SPAs

  • SPAs require special configuration for redirect URIs.
  • Use spa type for redirect URIs, supporting auth code flow with PKCE and CORS.
  • Backward-compatible with implicit flow.
  • Error handling for incorrect CORS setup provided.

Requesting Authorization Code

  • Begins with directing the user to the /authorize endpoint.
  • Includes permissions such as openid, offline_access, etc.
  • Admin-restricted permissions require global administrator consent.
  • Default behavior outlined for omitted optional parameters.

Code Flow Request Parameters

  • tenant: Controls sign-in scope.
  • client_id: Application ID assigned to app.
  • response_type: Must include code.
  • redirect_uri: Must match registered URIs.
  • scope: List of scopes requiring user consent.
  • response_mode: Specifies token delivery method.
  • state: Protects against CSRF attacks.

Successful and Error Responses

  • Successful response includes authorization_code and state.
  • Error responses include error and error_description for debugging.

Hybrid Flow

  • Requests both an ID token and authorization code.
  • Involves additional parameters like nonce for security.

Redeeming a Code for an Access Token

  • Confidential clients use client secrets or certificates.
  • Public clients must not use secrets or certificates.
  • Supports both client data for additional security.

Using the Access Token

  • Tokens used in API requests via the Authorization header.

Refreshing the Access Token

  • Access tokens are short-lived; refresh after expiration.
  • Refresh tokens are long-lived but may require handling errors.
  • Refresh tokens for SPAs are limited to 24 hours.

Error Codes for Token Endpoint

  • Various error codes help diagnose issues like invalid_request, unauthorized_client, etc.

Next Steps

  • Explore MSAL JS samples and learn about token exchange scenarios.

Additional Resources

  • Links to detailed documentation, MSAL libraries, and error handling guides.