DEV Community

Cover image for Mastering OAuth 2.0: Step by Step
Leapcell
Leapcell

Posted on

Mastering OAuth 2.0: Step by Step

Image description

Leapcell: The Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis

A Concise and Easy-to-Understand Explanation of OAuth 2.0

OAuth is an open network standard for authorization that is widely used globally, and the current version is 2.0. This article will provide a concise and easy-to-understand explanation of the design concept and operation process of OAuth 2.0 based on RFC 6749.

I. Application Scenarios

To help understand the applicable scenarios of OAuth, let's first look at a hypothetical example. Suppose there is a website named "Cloud Photo Printing" that can print out the photos stored by users on Google. If users want to use this service, they must allow "Cloud Photo Printing" to read their photos stored on Google.

Here is a key issue: Google will only allow "Cloud Photo Printing" to read these photos after obtaining the user's authorization. So, how can "Cloud Photo Printing" obtain the user's authorization?

The traditional method is for the user to tell "Cloud Photo Printing" their Google username and password, so that "Cloud Photo Printing" can read the user's photos. However, this approach has many serious disadvantages:

  1. Security Risk of Password Storage: In order to provide follow-up services, "Cloud Photo Printing" will store the user's password, which brings great security risks.
  2. Security Issue of the Login Method: Google has to use the password login method, but the simple password login has poor security.
  3. Lack of Permission Control: "Cloud Photo Printing" will have the right to access all the materials stored by the user on Google, and the user cannot limit the scope and validity period of the authorization obtained by "Cloud Photo Printing".
  4. High Cost of Revoking Authority: The user can only revoke the authority given to "Cloud Photo Printing" by changing the password. But doing so will cause all other third-party applications that have obtained the user's authorization to become invalid.
  5. High Risk of Data Leakage: As long as one third-party application is cracked, it will lead to the leakage of the user's password and all the data protected by the password.

And OAuth was born precisely to solve these problems.

II. Noun Definitions

Before explaining OAuth 2.0 in detail, it is necessary to understand several specialized nouns first. These nouns are extremely important for understanding the subsequent content, especially the relevant diagrams.

  1. Third - party application (Third-party Application): Also known as the "client" in this article, such as "Cloud Photo Printing" in the example of the previous section.
  2. HTTP service (HTTP Service Provider): Abbreviated as the "service provider" in this article, such as Google in the example of the previous section.
  3. Resource Owner (Resource Owner): Also known as the "user" in this article.
  4. User Agent (User Agent): In this article, it refers to the browser.
  5. Authorization server (Authorization Server): That is, the server specifically used by the service provider to handle authentication.
  6. Resource server (Resource Server): That is, the server where the service provider stores the resources generated by the user. It can be the same server as the authentication server or a different server.

After understanding the above nouns, it is not difficult to understand the role of OAuth, that is, to allow the "client" to obtain the authorization of the "user" safely and controllably, and then interact with the "service provider".

III. The Concept of OAuth

OAuth sets up an authorization layer between the "client" and the "service provider". The "client" cannot directly log in to the "service provider", but logs in to the authorization layer, so as to distinguish the user from the client. The token used by the "client" to log in to the authorization layer is different from the user's password, and the user can specify the permission scope and validity period of the authorization layer token when logging in.

After the "client" logs in to the authorization layer, the "service provider" will open the user's stored materials to the "client" according to the permission scope and validity period of the token.

IV. Operation Process

The operation process of OAuth 2.0 is shown in the following figure (extracted from RFC 6749):

  1. (A): After the user opens the client, the client requests authorization from the user.
  2. (B): The user agrees to grant authorization to the client.
  3. (C): The client uses the authorization obtained in the previous step to apply for a token from the authentication server.
  4. (D): The authentication server authenticates the client, and if there is no problem, it agrees to issue the token.
  5. (E): The client uses the token to apply to the resource server for obtaining resources.
  6. (F): The resource server confirms that the token is correct and agrees to open the resources to the client.

Among these six steps, step B is the key, that is, how the user grants authorization to the client. With this authorization, the client can obtain the token and then obtain the resources with the token. Next, the four modes for the client to obtain authorization will be explained one by one.

V. The Authorization Modes of the Client

The client must obtain the user's authorization (authorization grant) before it can obtain the token (access token). OAuth 2.0 defines the following four authorization methods:

  1. Authorization code mode (authorization code)
  2. Simplified mode (implicit)
  3. Password mode (resource owner password credentials)
  4. Client mode (client credentials)

VI. Authorization Code Mode

The authorization code mode (authorization code) is the most complete in function and the most rigorous in process among the authorization modes. Its characteristic is that it interacts with the authentication server of the "service provider" through the background server of the client. The specific steps are as follows:

  1. (A): The user accesses the client, and the client redirects the user to the authentication server.
  2. (B): The user chooses whether to grant authorization to the client.
  3. (C): Assuming that the user grants authorization, the authentication server redirects the user to the "redirection URI" (redirection URI) specified in advance by the client, and attaches an authorization code at the same time.
  4. (D): The client receives the authorization code, attaches the previous "redirection URI", and applies for a token from the authentication server. This step is completed on the background server of the client and is invisible to the user.
  5. (E): The authentication server checks the authorization code and the redirection URI. If there is no problem, it sends an access token (access token) and a refresh token (refresh token) to the client.

The following are the parameters required for the above steps:

  • Step A: The URI for the client to apply for authentication contains the following parameters:
    • response_type: Represents the authorization type, which is a required parameter, and the value here is fixed as "code".
    • client_id: Represents the ID of the client, which is a required parameter.
    • redirect_uri: Represents the redirection URI, which is an optional parameter.
    • scope: Represents the requested permission scope, which is an optional parameter.
    • state: Represents the current state of the client, and any value can be specified. The authentication server will return this value unchanged.

For example:

GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.leapcell.io
Enter fullscreen mode Exit fullscreen mode
  • Step C: The URI that the server responds to the client contains the following parameters:
    • code: Represents the authorization code, which is a required parameter. This code has a very short validity period, usually set to 10 minutes, and the client can only use this code once, otherwise it will be rejected by the authorization server. This code corresponds one-to-one with the client ID and the redirection URI.
    • state: If the client request contains this parameter, the response of the authentication server must also contain this parameter exactly the same.

For example:

HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlqweqwWxSbIA&state=xyz
Enter fullscreen mode Exit fullscreen mode
  • Step D: The HTTP request for the client to apply for a token from the authentication server contains the following parameters:
    • grant_type: Represents the authorization mode used, which is a required parameter, and the value here is fixed as "authorization_code".
    • code: Represents the authorization code obtained in the previous step, which is a required parameter.
    • redirect_uri: Represents the redirection URI, which is a required parameter and must be consistent with the value of this parameter in step A.
    • client_id: Represents the client ID, which is a required parameter.

For example:

POST /token HTTP/1.1
Host: server.leapcell.io
Authorization: Basic czZCaGRrwrqw0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
Enter fullscreen mode Exit fullscreen mode
  • Step E: The HTTP response sent by the authentication server contains the following parameters:
    • access_token: Represents the access token, which is a required parameter.
    • token_type: Represents the token type. This value is case-insensitive and is a required parameter. It can be of the bearer type or the mac type.
    • expires_in: Represents the expiration time, in seconds. If this parameter is omitted, the expiration time must be set through other means.
    • refresh_token: Represents the refresh token, which is used to obtain the next access token and is an optional parameter.
    • scope: Represents the permission scope. If it is consistent with the scope requested by the client, this item can be omitted.

For example:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
    "access_token":"2YotnFqwrwqrqwCsicMWpAA",
    "token_type":"example",
    "expires_in":3600,
    "refresh_token":"tGzv3JOqweqweTlKWIA",
    "example_parameter":"example_value"
}
Enter fullscreen mode Exit fullscreen mode

It can be seen from the above code that the relevant parameters are sent in JSON format (Content - Type: application/json), and it is clearly specified in the HTTP header information that caching is not allowed.

VII. Simplified Mode

The simplified mode (implicit grant type) does not go through the server of the third-party application, but directly applies for a token from the authentication server in the browser, skipping the step of the "authorization code", hence the name. All steps are completed in the browser, the token is visible to the visitor, and the client does not need to be authenticated. The specific steps are as follows:

  1. (A): The client redirects the user to the authentication server.
  2. (B): The user decides whether to grant authorization to the client.
  3. (C): Assuming that the user grants authorization, the authentication server redirects the user to the "redirection URI" specified by the client, and includes the access token in the Hash part of the URI.
  4. (D): The browser sends a request to the resource server, which does not contain the Hash value received in the previous step.
  5. (E): The resource server returns a web page, and the code contained in it can obtain the token in the Hash value.
  6. (F): The browser executes the script obtained in the previous step and extracts the token.
  7. (G): The browser sends the token to the client.

The following are the parameters required for the above steps:

  • Step A: The HTTP request sent by the client contains the following parameters:
    • response_type: Represents the authorization type, and the value here is fixed as "token", which is a required parameter.
    • client_id: Represents the ID of the client, which is a required parameter.
    • redirect_uri: Represents the redirection URI, which is an optional parameter.
    • scope: Represents the permission scope, which is an optional parameter.
    • state: Represents the current state of the client, and any value can be specified. The authentication server will return this value unchanged.

For example:

GET /authorize?response_type=token&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.leapcell.io
Enter fullscreen mode Exit fullscreen mode
  • Step C: The URI that the authentication server responds to the client contains the following parameters:
    • access_token: Represents the access token, which is a required parameter.
    • token_type: Represents the token type. This value is case-insensitive and is a required parameter.
    • expires_in: Represents the expiration time, in seconds. If this parameter is omitted, the expiration time must be set through other means.
    • scope: Represents the permission scope. If it is consistent with the scope requested by the client, this item can be omitted.
    • state: If the client request contains this parameter, the response of the authentication server must also contain this parameter exactly the same.

For example:

HTTP/1.1 302 Found
Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=example&expires_in=3600
Enter fullscreen mode Exit fullscreen mode

In the above example, the authentication server uses the Location column of the HTTP header information to specify the URL that the browser redirects to. Note that the Hash part of this URL contains the token. According to step D, the browser will visit the URL specified by Location in the next step, but the Hash part will not be sent. In the next step E, the code sent by the resource server of the service provider will extract the token in the Hash.

VIII. Password Mode

In the password mode (Resource Owner Password Credentials Grant), the user provides their own username and password to the client, and the client uses this information to request authorization from the "service provider". In this mode, the user must provide their password to the client, but the client is not allowed to store the password. This is usually used in cases where the user has a high degree of trust in the client, for example, the client is part of the operating system or is produced by a well-known company. And the authentication server will only consider adopting this mode when other authorization modes cannot be executed. The specific steps are as follows:

  1. (A): The user provides the username and password to the client.
  2. (B): The client sends the username and password to the authentication server and requests a token from the latter.
  3. (C): After the authentication server confirms that there is no problem, it provides an access token to the client.

In step B, the HTTP request sent by the client contains the following parameters:

  • grant_type: Represents the authorization type, and the value here is fixed as "password", which is a required parameter.
  • username: Represents the username, which is a required parameter.
  • password: Represents the user's password, which is a required parameter.
  • scope: Represents the permission scope, which is an optional parameter.

For example:

POST /token HTTP/1.1
Host: server.leapcell.io
Authorization: Basic czZCaGRSa3F0gertetewrmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=A3ddj3w
Enter fullscreen mode Exit fullscreen mode

In step C, the authentication server sends an access token to the client, for example:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
    "access_token":"2YotnFZqweqwreqwrpAA",
    "token_type":"example",
    "expires_in":3600,
    "refresh_token":"tGzv3rewrewrtr2TlKWIA",
    "example_parameter":"example_value"
}
Enter fullscreen mode Exit fullscreen mode

The meanings of the various parameters in the above code can refer to the section "Authorization Code Mode". Throughout the process, the client is not allowed to save the user's password.

IX. Client Mode

The client mode (Client Credentials Grant) means that the client authenticates with the "service provider" in its own name, not in the name of the user. Strictly speaking, the client mode does not belong to the problem that the OAuth framework needs to solve. In this mode, the user registers directly with the client, and the client requests the "service provider" to provide services in its own name. In fact, there is no authorization problem. The specific steps are as follows:

  1. (A): The client authenticates its identity with the authentication server and requests an access token.
  2. (B): After the authentication server confirms that there is no problem, it provides an access token to the client.

In step A, the HTTP request sent by the client contains the following parameters:

  • grant_type: Represents the authorization type, and the value here is fixed as "client_credentials", which is a required parameter.
  • scope: Represents the permission scope, which is an optional parameter.

For example:

POST /token HTTP/1.1
Host: server.leapcell.io
Authorization: Basic czZCaGRSqeqwewqmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
Enter fullscreen mode Exit fullscreen mode

The authentication server must verify the identity of the client through some means.

In step B, the authentication server sends an access token to the client, for example:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
    "access_token":"2Yotnqweqwe1zCsicMWpAA",
    "token_type":"example",
    "expires_in":3600,
    "example_parameter":"example_value"
}
Enter fullscreen mode Exit fullscreen mode

The meanings of the various parameters in the above code can refer to the section "Authorization Code Mode".

X. Updating the Token

If the client's "access token" has expired when the user accesses, the "refresh token" needs to be used to apply for a new access token. The HTTP request sent by the client to update the token contains the following parameters:

  • grant_type: Represents the authorization mode used, and the value here is fixed as "refresh_token", which is a required parameter.
  • refresh_token: Represents the previously received refresh token, which is a required parameter.
  • scope: Represents the requested authorization scope, which cannot exceed the scope of the previous application. If this parameter is omitted, it means the same as the previous one.

For example:

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzqeqweqwmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA
Enter fullscreen mode Exit fullscreen mode

Leapcell: The Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis

Finally, I recommend the best platform for deployment: Leapcell

Image description

1. Multi-Language Support

  • Develop with JavaScript, Python, Go, or Rust.

2. Deploy unlimited projects for free

  • Pay only for usage β€” no requests, no charges.

3. Unbeatable Cost Efficiency

  • Pay-as-you-go with no idle charges.
  • Example: $25 supports 6.94M requests at a 60ms average response time.

4. Streamlined Developer Experience

  • Intuitive UI for effortless setup.
  • Fully automated CI/CD pipelines and GitOps integration.
  • Real-time metrics and logging for actionable insights.

5. Effortless Scalability and High Performance

  • Auto-scaling to handle high concurrency with ease.
  • Zero operational overhead β€” just focus on building.

Image description

Explore more in the documentation!

Leapcell Twitter: https://x.com/LeapcellHQ

Top comments (0)