
Navigation
- What is OAuth?
- Why OAuth 2.1?
- Main roles
- Authorization Code Flow with PKCE
- Tokens: access and refresh
- Best practices
1. What is OAuth?
OAuth (Open Authorization) is an open standard for delegated authorization. It allows a user (resource owner) to grant a third-party application (client) limited access to protected resources on a resource server without sharing their credentials (username/password) with the client.
2. Why OAuth 2.1?
OAuth 2.0 became widely used but left room for insecure implementations (implicit flow, weak token handling, optional PKCE). OAuth 2.1 is not a brand-new protocol but a profile of OAuth 2.0 that mandates safer choices and removes insecure options.
Key changes introduced or enforced by OAuth 2.1:
- Implicit flow removed (no client-side tokens via redirect fragment).
- PKCE (Proof Key for Code Exchange) is required for all clients.
- Require HTTPS for all endpoints.
- Clarify token handling and refresh practices.
3. Main roles (actors)
- Resource Owner: the end-user who owns data.
- Client: the application requesting access (e.g., belkedah.com).
- Authorization Server: issues authorization codes and tokens (e.g., Google, GitHub).
- Resource Server: the API that hosts the user data.
4. Authorization Code Flow with PKCE (step-by-step)
The Authorization Code flow with PKCE is the recommended flow in OAuth 2.1 for both public and confidential clients.
- The client begins the flow by generating a code_verifier (random string) and deriving a code_challenge.
- The client redirects the user to the authorization server with the
code_challenge
and other parameters. - The user authenticates and consents on the authorization server.
- The authorization server redirects back to the client with an authorization code.
- The client exchanges the authorization code for an access token by sending the original
code_verifier
. - The authorization server validates the
code_verifier
against the earliercode_challenge
and issues tokens. - The client can now use the access token to call APIs on the resource server.
5. Tokens: access and refresh
- Access token: short-lived token used to call resource APIs.
- Refresh token: long-lived token used to obtain new access tokens without user interaction.
OAuth 2.1 encourages careful use of refresh tokens (rotation, revocation, bound to client) and strict storage rules (never store tokens in localStorage for single-page apps; use secure, httpOnly cookies or native secure storage).
6. Security best practices mandated or recommended by OAuth 2.1
- Use Authorization Code + PKCE for all clients.
- Use HTTPS for all endpoints and redirects.
- Avoid sending tokens in URLs or fragments.
- Implement refresh token rotation and detect reuse (replay detection).
- Use short-lived access tokens and minimal scopes.
- Use state parameter and nonce where appropriate to mitigate CSRF and replay attacks.