AnyLearn
All lessons
Programmingintermediate

OAuth 2.0: Deep Dive into Authorization Flows

Explore the core concepts of OAuth 2.0, its various grant types, and how it enables secure, delegated access without sharing credentials. Understand the roles and the step-by-step authorization process.

Not signed in — your progress and quiz score won't be saved.
Lesson progress1 / 12

What is OAuth 2.0?

OAuth 2.0 is an authorization framework that enables an application (client) to obtain limited access to an HTTP service (resource server) on behalf of a resource owner. It's crucial to understand that OAuth is not an authentication protocol; it's about authorization – granting permissions, not verifying identity. Think of it as a valet key for your car: you give the valet a key that only allows them to drive and park, not open the trunk or glove compartment. This delegated access avoids the insecure practice of sharing the user's primary credentials (username and password) directly with the client application.

Full lesson text

All 12 steps on one page — for reading, reference, and search.

Show

1. What is OAuth 2.0?

OAuth 2.0 is an authorization framework that enables an application (client) to obtain limited access to an HTTP service (resource server) on behalf of a resource owner. It's crucial to understand that OAuth is not an authentication protocol; it's about authorization – granting permissions, not verifying identity. Think of it as a valet key for your car: you give the valet a key that only allows them to drive and park, not open the trunk or glove compartment. This delegated access avoids the insecure practice of sharing the user's primary credentials (username and password) directly with the client application.

2. The Four Key Roles

Understanding the interaction in OAuth 2.0 requires recognizing four distinct roles:

  1. Resource Owner: The user who owns the protected resources (e.g., their photos on a social media site). They grant permission for a client to access these resources.
  2. Client: The application requesting access to the resource owner's protected resources. This could be a web app, mobile app, or even a server-side application.
  3. Authorization Server: The server that authenticates the resource owner and issues access tokens to the client after obtaining authorization. It's the gatekeeper.
  4. Resource Server: The server hosting the protected resources. It accepts and validates access tokens to respond to client requests (e.g., retrieving user data).

3. OAuth 2.0 Roles Interaction

High-level flow showing the interaction between the four key roles in OAuth 2.0.

flowchart TD
  ResourceOwner["Resource Owner (User)"]
  Client["Client Application"] --> ResourceServer["Resource Server (API)"]
  AuthorizationServer["Authorization Server"]

  ResourceOwner -- "Grants Consent" --> AuthorizationServer
  Client -- "Requests Authorization" --> AuthorizationServer
  AuthorizationServer -- "Issues Access Token" --> Client
  Client -- "Uses Access Token for Data" --> ResourceServer
  ResourceServer -- "Returns Protected Data" --> Client

4. Authorization Grant Types

OAuth 2.0 defines several 'grant types', which are methods a client uses to obtain an access token. The choice of grant type depends on the client's nature (e.g., confidential web app vs. public mobile app) and the level of trust. The most common and secure grant type for web applications is the Authorization Code flow. Others include the Client Credentials flow for machine-to-machine communication, and the Implicit flow, which is now largely deprecated due to security concerns.

Heads up: The Password Grant Type is also deprecated and should be avoided in new applications due to the direct handling of user credentials by the client.

5. Deep Dive: Authorization Code Flow (Part 1)

The Authorization Code flow is considered the most secure and widely used for confidential clients (like traditional web applications that can securely store client secrets). It involves several redirects and a temporary authorization code.

Here's the initial sequence:

  1. The client application redirects the resource owner's browser to the Authorization Server's authorization endpoint. This request includes the client_id, requested scopes, a redirect_uri, and a response_type=code.
  2. The Authorization Server authenticates the resource owner (if not already logged in) and prompts them to grant or deny the client's requested permissions.
  3. If the resource owner grants permission, the Authorization Server redirects the browser back to the redirect_uri provided by the client, including a one-time authorization_code.

6. Deep Dive: Authorization Code Flow (Part 2)

After receiving the authorization_code, the client application performs a crucial server-to-server step:

  1. The client's backend server sends a POST request directly to the Authorization Server's token endpoint. This request includes the authorization_code, client_id, client_secret (if confidential client), redirect_uri, and grant_type=authorization_code.
  2. The Authorization Server validates the code and client credentials. If valid, it responds with an Access Token (and often a Refresh Token).
  3. The client uses this Access Token to make authenticated requests to the Resource Server. The Access Token is typically a Bearer token, sent in the Authorization header: Authorization: Bearer <access_token>.

7. Authorization Code Flow Steps

Detailed sequence of the Authorization Code grant type.

sequenceDiagram
  actor User
  participant Client["Client App"] as Client
  participant AuthZServer["Authorization Server"] as AuthZServer
  participant ResServer["Resource Server"] as ResServer

  User->>Client: Clicks Login
  Client->>AuthZServer: Sends Redirect
  AuthZServer->>User: Prompts for Consent
  User->>AuthZServer: Grants Consent
  AuthZServer->>Client: Sends Code Redirect
  Client->>AuthZServer: Exchanges Code
  AuthZServer->>Client: Returns Tokens
  Client->>ResServer: Requests Protected Data
  ResServer->>Client: Returns Data

8. Client Credentials Flow

The Client Credentials flow is used for machine-to-machine authentication, where an application needs to access its own resources or resources of the Resource Server, not on behalf of a specific user. There's no user involved in the authorization step.

Steps:

  1. The client makes a POST request to the Authorization Server's token endpoint, sending its client_id and client_secret (if applicable) in the request body, along with grant_type=client_credentials.
  2. The Authorization Server authenticates the client and, if valid, returns an Access Token.
  3. The client then uses this Access Token to access resources on the Resource Server.

This flow is ideal for service accounts, daemons, or other non-interactive clients that operate independently of a user.

9. Access Tokens and Refresh Tokens

Access tokens are the credentials used by the client to access protected resources on the Resource Server. They are typically short-lived for security reasons (e.g., 5-60 minutes).

Refresh tokens, on the other hand, are long-lived credentials issued by the Authorization Server to the client. Their purpose is to obtain new access tokens without requiring the resource owner to re-authorize the client. When an access token expires, the client can send its refresh token to the Authorization Server's token endpoint (with grant_type=refresh_token) to get a fresh access token. This significantly improves user experience by reducing re-authentication prompts while maintaining security.

10. Scopes: Limiting Access

Scopes are a crucial part of OAuth 2.0, allowing the client to specify the exact permissions it needs from the resource owner. They represent fine-grained access levels, ensuring the client only gets the minimum necessary access to resources. For example:

  • read:profile: Permission to read user profile information.
  • write:photos: Permission to upload photos.
  • read:email: Permission to read the user's email address.

When the client requests authorization, it includes the desired scopes. The Authorization Server presents these to the resource owner, who can then review and approve (or deny) them. This prevents a client from requesting, for example, access to a user's entire account when it only needs to read their public profile.

11. Example: Requesting an Access Token (Simplified)

While full implementations involve redirects and server-side logic, here's a conceptual look at the token exchange POST request in the Authorization Code flow. This happens from your backend server.

    POST /token HTTP/1.1
    Host: auth.example.com
    Content-Type: application/x-www-form-urlencoded

    grant_type=authorization_code&
    code=SplWfygP7Xh...&
    redirect_uri=https://client.example.com/callback&
    client_id=your_client_id&
    client_secret=your_client_secret
    ```

The Authorization Server would respond with something like this:

```json
    HTTP/1.1 200 OK
    Content-Type: application/json

    {
      "access_token": "eyJraWQiOiJ...",
      "token_type": "Bearer",
      "expires_in": 3600,
      "refresh_token": "eyJSbGciOiJ...",
      "scope": "read:profile write:posts"
    }
    ```

12. Security Best Practices

Implementing OAuth 2.0 securely requires adherence to best practices:

  • Always use HTTPS/TLS: All communication between client, Authorization Server, and Resource Server must be encrypted.
  • Validate redirect_uri: The Authorization Server must strictly validate the redirect_uri against pre-registered values to prevent redirection attacks.
  • Use PKCE (Proof Key for Code Exchange): Essential for public clients (mobile/SPA) using the Authorization Code flow to prevent authorization code interception attacks.
  • Keep client_secret confidential: For confidential clients, the secret must be securely stored and never exposed in client-side code.
  • Strict Scope Management: Only request the minimum necessary scopes and ensure the user understands what they are granting.
  • Regular Token Rotation: Refresh tokens should have a reasonable lifetime and be rotated or revoked when compromised.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. What is the primary purpose of OAuth 2.0?
    • To authenticate users directly with client applications.
    • To authorize client applications to access protected resources on behalf of a user.
    • To provide a single sign-on (SSO) solution across multiple services.
    • To encrypt data transmission between client and server.
  2. Which OAuth 2.0 role is responsible for issuing access tokens to the client?
    • Resource Owner
    • Client
    • Authorization Server
    • Resource Server
  3. In the Authorization Code flow, what does the client send to the Authorization Server's token endpoint to obtain an access token?
    • The user's username and password.
    • A refresh token.
    • The authorization code, along with client ID and secret (for confidential clients).
    • The access token received from the Resource Server.
  4. What is the primary benefit of using Refresh Tokens?
    • They act as an alternative to access tokens for accessing resources.
    • They extend the lifespan of access tokens indefinitely.
    • They allow a client to obtain new access tokens without user re-authentication.
    • They are used by the Resource Server to validate incoming requests.
  5. Which of the following is considered a security best practice for OAuth 2.0 implementations?
    • Embedding client secrets directly into mobile application code.
    • Using HTTP instead of HTTPS for faster communication.
    • Strictly validating the `redirect_uri` to prevent attacks.
    • Requesting the broadest possible scopes to cover all future needs.

Related lessons