Blog | G5 Cyber Security

OAuth 2.0: Authorisation Code Flow

TL;DR

This guide explains how to get an authorisation code and exchange it for an access token in OAuth 2.0, the most common way applications gain limited access to a user’s resources without needing their password.

Understanding the Flow

The Authorisation Code flow involves these steps:

  1. Your application asks the user for permission to access their data.
  2. If granted, the authorisation server redirects the user back to your application with an authorisation code.
  3. Your application exchanges this code for an access token (and often a refresh token).
  4. Your application uses the access token to access the user’s resources.

Step 1: Redirecting to the Authorisation Server

You need to build a URL that points to the authorisation server’s authorisation endpoint. This URL includes several parameters:

Example URL:

https://example.com/oauth2/authorise?client_id=YOUR_CLIENT_ID&redirect_uri=https%3A%2F%2Fyour-app.com%2Fcallback&response_type=code&scope=profile+email&state=RANDOM_STATE

Redirect the user’s browser to this URL.

Step 2: Handling the Redirect from the Authorisation Server

After the user authenticates and grants (or denies) permission, the authorisation server redirects them back to your redirect_uri with an authorisation code in the query parameters. The response will also include the state parameter.

Example redirect URL (success):

https://your-app.com/callback?code=AUTHORISATION_CODE&state=RANDOM_STATE

Step 3: Exchanging the Authorisation Code for an Access Token

Make a POST request to the authorisation server’s token endpoint. This request requires:

Example POST request (using curl):

curl -X POST 
  -H "Content-Type: application/x-www-form-urlencoded" 
  -d 'client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&code=AUTHORISATION_CODE&redirect_uri=https%3A%2F%2Fyour-app.com%2Fcallback&grant_type=authorization_code' 
  https://example.com/oauth2/token

Step 4: Receiving the Access Token

The token endpoint will respond with a JSON object containing:

Example response:

{ 
  "access_token": "ACCESS_TOKEN", 
  "token_type": "Bearer", 
  "expires_in": 3600, 
  "refresh_token": "REFRESH_TOKEN" 
}

Step 5: Using the Access Token

Include the access token in the Authorization header of your requests to protected resources. Typically using Bearer authentication:

Authorization: Bearer ACCESS_TOKEN

The server will validate the token and grant (or deny) access based on its permissions.

Exit mobile version