OAuth 2.0 Flows: A Complete Guide to Authorization Code, Authorization Code with PKCE & Device Code.

Illustration photo for oauth 2.0

In this course, we'll explore OAuth 2.0 authorization flows in depth. This course is specifically designed for developers who need to integrate OAuth 2.0 into their applications. If you're looking for a high-level overview of OAuth 2.0, you'll find many online resources and blogs that can provide a good starting point. However, if you're ready to dive deeper and gain hands-on experience with implementing OAuth 2.0, this course is perfect for you.

A brief introduction to Oauth 2.0

OAuth 2.0 is an authorization protocol that enables secure delegation of access to protected resources. Let's illustrate its purpose with a real-world scenario. Imagine a user who stores documents in Service A (Resource server). Now, suppose the user wants to connect Service B (Client app) to their data in Service A, but only grant limited access to specific actions, such as reading data. Instead of sharing their login credentials with Service B, the user wants to authorize Service B to perform only the desired actions, without compromising their overall security.

Oauth 2.0 Authorization code flow diagram

Oauth 2.0 Authorization code flow diagram

To make this work, Service A and Service B need to establish a trusted relationship, which is where OAuth 2.0 comes in. By using OAuth 2.0, Service A and Service B can communicate securely, allowing the user to grant specific permissions to Service B without exposing their sensitive credentials. This way, the user can enjoy the benefits of integrating Service B with their data in Service A, while maintaining control over their authorization and security.

Registering the client application

Service B, which acts as the client, must register in the authorization server used by Service A. As part of the registration process, the client will receive a unique client ID and client secret and provide a redirect URI to be called by the resource server in the flows.

Choose the right flow

The type of client (web app, mobile app, TV app, etc.) will determine which OAuth 2.0 flow to use. In the following sections, we'll delve into some of the most commonly used flows and walk you through the step-by-step communication process between the user, client, authorization server, and resource server.

OAuth 2.0 Authorization Code flow

The authorization code flow is designed for applications with a secure backend, such as traditional web apps or mobile apps with a server component. To implement this flow in your application here is a step by step guide to the communication between your application and the authorization and resource servers.

Step 1: Redirect the user to the Authorization Server (AS)

The flow start by a user connecting to the client application. The client must first build the authorization URL and forward the user to it.

The URL contains the authorize endpoint of the Authorization Server, the response type (in this case code which mean that the client app want to get the authorization code), the client ID, the redirect URI (The Authorization Server will forward the user to this URL after the authentification), the scope and a state (a random string that must be generated and stored by the client, and will be used in the next steps for verification)

The authorization URL is similar to this one:

1GET https://workflows.guru/authorize?response_type=code
2
3&client_id=<The client ID>
4&redirect_uri=<The callback URI>
5&scope=<Any string could be read-photos or write-video ...>
6&state=< A random string>

Scope is not specified by the OAuth 2.0 protocol. It can be any string and depends on the provider's implementation.

After the redirection, the user will be requested to login and approve the scope, this authentification step is not in the scope of OAuth 2.0 it could be handled in different ways, let's say that the user will login using his username and password to the resourse server.

Step 2: Redirection from Authorization server to client app

After a successfull login, the user will be redirected back to the client. The redirection contains two valuable data, the authorization code as well as the state that was send by the client at first. The client must verify if the state match the state that was generate in the first step.

Step 3: Exchange the Authorization Code for an Access Token

Now that the client have the authorization code, it must exchange it for an access token in a back channel communication.

This time, the client will send a POST request to the token endpoint providing the authorization code as well as the client ID and client secret, similar to the following request:

1POST https://workflows.guru/token
2
3grant_type=authorization_code
4&client_id="Client ID"
5&client_secret="Client secret"
6&redirect_uri="callback URI"
7&code="authorization code"

If everything is OK, the AS will send a response containing, the access token. The access token must be used by the client app in every request to the resource server.

Following is an example of a response from the AS to the client:

1{
2 "token_type": "Bearer",
3 "expires_in": 86400,
4 "access_token": "G6i0rHWVBBFVHPKASHBFARKXlB3W09m7ovgjZynSD1BF5qElNg8",
5 "scope": "read-photos",
6 "refresh_token": "ksoqIfPHATSRDVMhsyatq10_sJ4ZtBV"
7}

OAuth 2.0 Authorization with PKCE flow

Authorization code flow with PKCE is similar to the authorization code flow with an additional feature to enhance security. It's primarily used in public clients, such as mobile or single-page applications, where storing a client secret securely isn't possible.

Step 1: Redirect the user to the AS

Before redirecting the user to the authorization server, the client first generates a secret code verifier (a random string between 43 and 128 characters), and then create the code challenge using the generated code verifier. The code challenge is a BASE64 URL encoded string of the SHA256 hash of the code verifier.

The client needs to store the secret code for later use. The Authorization URL is constracted the same way as in the authorization code flow but include two other data the code challenge and the protocol used in the hash operation.

So, the client store the random code generated and send the hashed version to the server. The server stores this hash to verify the client during the authorization code exchange step.

Step 2: Redirection from AS to client app

As in the authorization code flow, the user will be redirected to the redirect URI including the authorization code and state in the query parameters.

Step 3: Exchange the Authorization Code for an Access Token

The client send a POST request to the token endpoint and include the code verifier along with the other information (grant_type, client_id, client_secret, redirect_uri, code)

1grant_type="authorization_code"
2client_id="client id"
3client_secret="client secret"
4redirect_uri="redirect URI"
5code="authorization code"
6code_verifier="The random coded generated in the first step, NOT HASHED"

The authorization server already have the hashed version (The code challenge) will hash the code verifier and compare it to the stored hash. This ensures that a malicious party that intercepted the authorization code will not be able to use it.

If everything is OK, the client app will receive a token response as follow:

1{
2 "token_type": "Bearer",
3 "expires_in": 86400,
4 "access_token": "Uzpc9F2d6p3NcPLIKAU89AGYSHAQSXMMbfGaXE7t-nRn",
5 "scope": "read-photos",
6 "refresh_token": "ysRPGATRS-thc3Kbtj4eUxQ9h"
7}

OAuth 2.0 Device Code Flow

The OAuth 2.0 Device Code Flow is designed for devices with limited input capabilities, such as smart TVs, IoT devices, or command-line tools.

The first step of the Device flow is to request a device code. This is done with a simple POST request to the device code endpoint.

1POST https://workflows.guru/device

User enter the Code

The response from the server includes the device code, a code to display to the user, and the URL the user should visit to enter the code, as follow:

1{
2 "device_code": "NGU5OWFiNjQ5YmQwNGY3YTdmZTEyNzQ3YzQ1YSA",
3 "user_code": "BDWD-HQPK",
4 "verification_uri": "https://workflows.guru/device",
5 "interval": 5,
6 "expires_in": 1800
7}

The user must enter the user_code in the URL provided in the verification_uri.

Poll the authorization server periodically

The client need to poll the token endpoint with the device code until an access token or error is returned.

1POST https://workflows.guru/token
2grant_type="device_code grant type"
3&client_id=""the client id"
4&device_code=" the device code"
5

Before the user has finished signing in and approving the request, the authorization server will return a status indicating the authorization is still pending.

1HTTP/1.1 400 Bad Request
2{
3 "error": "authorization_pending"
4}
5

When the user approves the request, the token endpoint will respond with the access token.

1HTTP/1.1 200 OK
2{
3 "token_type": "Bearer",
4 "access_token": "GuruPrzhatsgtan430zqMLgV3Ia",
5 "expires_in": 3600,
6 "refresh_token": "guruahdtz798aassb3a276c2aab35e97298a060e0ede5b43ed1f720a8"
7}
8

Now the device can use this access token to make API requests on behalf of the user.

Difference betweeen Oauth 2.0 and OpenID connect (OIDC)

OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0, enabling applications to verify a user's identity and obtain profile information. To implement this, OpenID Connect includes additional features, such as:

  • Add the ID token + the Access Token
  • The use of JWT for ID token
  • Add a new endpoint to get user info /userinfo endpoint
  • Add /.well-known/openid-configuration

Without OIDC the client app can check if the user is authorized or not but it does not know who the user is. Using JWT standard in the ID token allow the client application to decode the user information, the client could also request more information about the user by calling the userinfo endpoint.

Conclusion

The OAuth protocol has become a widely adopted standard for implementing authorization in a vast array of applications. Throughout this course, we've gained a comprehensive understanding of the most commonly used OAuth flows.

If you have any concerns, questions or suggestions please send us an email to contact@workflows.guru