OAuth2

OAuth is an open network standard for authorization and is widely used around the world. The current version is version 2.0.

This article gives a concise and popular explanation of the design idea and operation process of OAuth 2.0. The main reference material is RFC 6749 .

An application scenario

To understand where OAuth is applicable, let me take a hypothetical example.

There is a "cloud printing" website, which can print photos of users stored in Google. In order to use the service, users must let "cloud printing" read their photos stored on Google.

cloud printing

The problem is that Google will only allow "cloud printing" to read these photos with the user's authorization. Then, how does "Cloud Printing" obtain the authorization of users?

The traditional method is that users tell "cloud printing" their Google username and password, and the latter can read the user's photo. This approach has the following serious disadvantages.

(1)"云冲印"为了后续的服务,会保存用户的密码,这样很不安全。

(2)Google不得不部署密码登录,而我们知道,单纯的密码登录并不安全。

(3)"云冲印"拥有了获取用户储存在Google所有资料的权力,用户没法限制"云冲印"获得授权的范围和有效期。

(4)用户只有修改密码,才能收回赋予"云冲印"的权力。但是这样做,会使得其他所有获得用户授权的第三方应用程序全部失     效。

(5)只要有一个第三方应用程序被破解,就会导致用户密码泄漏,以及所有被密码保护的数据泄漏。

OAuth was born to solve these problems.

two noun definitions

Before explaining OAuth 2.0 in detail, it is necessary to understand a few specific terms. They are crucial to reading the explanations that follow, especially the pictures.

(1)Third-party application:第三方应用程序,本文中又称"客户端"(client),即上一节例子中的"云冲印"。An application making protected resource requests on behalf of the resource owner and with its authorization.  The term "client" does not imply any particular implementation characteristics (e.g., whether the application executes on a server, a desktop, or other devices)
(2)HTTP service:HTTP服务提供商,本文中简称"服务提供商",即上一节例子中的Google。
(3)Resource Owner:资源所有者,本文中又称"用户"(user)。
     An entity capable of granting access to a protected resource. When the resource  owner is a person, it is referred to as an end-user
(4)User Agent:用户代理,本文中就是指浏览器。
(5)Authorization server:认证服务器,即服务提供商专门用来处理认证的服务器。
    The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization
(6)Resource server:资源服务器,即服务提供商存放用户生成的资源的服务器。它与认证服务器,可以是同一台服务器,也可以是不同的服务器。
    The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens.

Knowing the above terms, it is not difficult to understand that the role of OAuth is to allow the "client" to obtain the authorization of the "user" in a safe and controllable manner and interact with the "service provider".

Three OAuth Ideas

OAuth sets up an authorization layer between the "client" and the "service provider". The "client" cannot log into the "service provider" directly, only the authorization layer, which distinguishes the user from the client. The token used by the "client" to log in to the authorization layer, which is different from the user's password. 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" opens the user's stored data to the "client" according to the permission scope and validity period of the token.

run process

The operation flow of OAuth 2.0 is as follows, which is taken from RFC 6749 .

OAuth running process

(A)用户打开客户端以后,客户端要求用户给予授权。(The client requests authorization from the resource     owner.  The authorization request can be made directly to the resource owner(as shown), or     preferably indirectly via the authorizationserver as an intermediary.)

(B)用户同意给予客户端授权。(The client receives an authorization grant, which is acredential         representing the resource owner's authorization,expressed using one of four grant types       defined in this specification or using an extension grant type.  The authorization grant       type depends on the method used by the client to request authorization and the types           supported by the authorization server)

(C)客户端使用上一步获得的授权,向认证服务器申请令牌。
     The client requests an access token by authenticating with the
     authorization server and presenting the authorization grant
(D)认证服务器对客户端进行认证以后,确认无误,同意发放令牌。
    The authorization server authenticates the client and validates
    the authorization grant, and if valid, issues an access token
(E)客户端使用令牌,向资源服务器申请获取资源。
		The client requests the protected resource from the resource
    server and authenticates by presenting the access token
(F)资源服务器确认令牌无误,同意向客户端开放资源。
		The resource server validates the access token, and if valid,
    serves the request

Four-client authorization mode (Authorization Grant)

The client must be authorized by the user (authorization grant) in order to obtain the token (access token). OAuth 2.0 defines four authorization methods

  • Authorization code

  • Simplified mode (implicit)

  • Password mode (resource owner password credentials)

  • Client mode (client credentials)

Authorization code

The authorization code mode (authorization code) is the authorization mode with the most complete functions and the strictest process. Its characteristic is to interact with the authentication server of the "service provider" through the client's background server.

Authorization code mode

Its steps are as follows:

(A) The user accesses the client, which directs the former to the authentication server.

(B) The user chooses whether to authorize the client.

(C) Assuming that the user grants authorization, the authentication server directs the user to the "redirection URI" (redirection URI) specified in advance by the client, along with an authorization code.

(D) The client receives the authorization code, attaches the earlier "redirect URI", and requests a token from the authentication server. This step is done on the server in the background of the client and is not visible to the user.

(E) The authentication server checks the authorization code and redirection URI, and after confirming that they are correct, sends an access token and a refresh token to the client.

Below are the parameters required for the above steps.

In step A, the URI for the client to apply for authentication includes the following parameters:

  • response_type: indicates the authorization type, required, the value here is fixed to "code"
  • client_id: indicates the ID of the client, required
  • redirect_uri: Indicates redirect URI, optional
  • Scope: Indicates the scope of permission to apply, optional
  • state: Indicates the current state of the client, any value can be specified, and the authentication server will return this value intact.

Below is an 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.example.com

In step C, the server responds to the client's URI with the following parameters:

  • code: Indicates the authorization code, which is required. The validity period of the code should be very short, usually set to 10 minutes, and the client can only use the code once, otherwise it will be rejected by the authorization server. There is a one-to-one correspondence between this code and the client ID and redirection URI.
  • state: If the client's request contains this parameter, the authentication server's response must also contain this parameter exactly.

Below is an example.


HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA
          &state=xyz

In step D, the client makes an HTTP request for a token from the authentication server, including the following parameters:

  • grant_type: Indicates the authorization mode used, a required option. The value here is fixed to "authorization_code".
  • code: indicates the authorization code obtained in the previous step, required.
  • redirect_uri: Indicates the redirection URI, which is required and must be the same as the parameter value in step A.
  • client_id: Indicates the client ID, required.

Below is an example.


POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

In step E, the HTTP reply sent by the authentication server contains the following parameters:

  • access_token: Indicates the access token, required.
  • token_type: Indicates the token type. The value is case-insensitive and required. It can be bearer type or mac type.
  • expires_in: Indicates the expiration time, in seconds. If this parameter is omitted, the expiration time must be set in other ways.
  • refresh_token: Indicates the update token, used to obtain the next access token, optional.
  • scope: Indicates the scope of authority. If it is consistent with the scope applied by the client, this item can be omitted.

Below is an example.


     HTTP/1.1 200 OK
     Content-Type: application/json;charset=UTF-8
     Cache-Control: no-store
     Pragma: no-cache

     {
       "access_token":"2YotnFZFEjr1zCsicMWpAA",
       "token_type":"example",
       "expires_in":3600,
       "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
       "example_parameter":"example_value"
     }

As you can see from the above code, the relevant parameters are sent in JSON format (Content-Type: application/json). Additionally, the HTTP headers explicitly specify that they must not be cached.

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 "authorization code" step, hence the name. All steps are done in the browser, the token is visible to the visitor, and the client does not require authentication.

simplified mode

Its steps are as follows:

(A) The client directs the user to the authentication server.

(B) The user decides whether to authorize the client.

(C) Assuming the user grants authorization, the authentication server directs the user to the "redirect URI" specified by the client and includes the access token in the Hash portion of the URI.

(D) The browser makes a request to the resource server, which does not include the hash value received in the previous step.

(E) The resource server returns a web page containing code to obtain the token in the hash value.

(F) The browser executes the script obtained in the previous step to extract the token.

(G) The browser sends the token to the client.

Below are the parameters required for the above steps.

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

  • response_type: Indicates the authorization type. The value here is fixed to "token", which is required.
  • client_id: Indicates the ID of the client, required.
  • redirect_uri: indicates the URI of redirection, optional.
  • scope: Indicates the permission scope, optional.
  • state: Indicates the current state of the client, any value can be specified, and the authentication server will return this value intact.

Below is an 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.example.com

In step C, the authentication server responds to the client's URI with the following parameters:

  • access_token: Indicates the access token, required.
  • token_type: Indicates the token type. This value is case-insensitive and required.
  • expires_in: Indicates the expiration time, in seconds. If this parameter is omitted, the expiration time must be set in other ways.
  • scope: Indicates the scope of authority. If it is consistent with the scope applied by the client, this item can be omitted.
  • state: If the client's request contains this parameter, the authentication server's response must also contain this parameter exactly.

Below is an example.


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

In the above example, the authentication server uses the Location field of the HTTP header to specify the URL to which the browser is redirected. Note that the token is included in the Hash portion of this URL.

According to Step D above, 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.

password mode

In password mode (Resource Owner Password Credentials Grant), the user provides the client with his username and password. The client uses this information to request authorization from the "service provider".

In this mode, the user must give his password to the client, but the client must not store the password. This is usually used when the user has high trust in the client, such as the client is part of the operating system, or is produced by a well-known company. The authentication server should only consider using this mode if other authorization modes cannot be implemented.

password mode

Its steps are as follows:

(A) The user provides the client with a username and password.

(B) The client sends the username and password to the authentication server and requests a token from the latter.

(C) After the authentication server confirms that it is correct, it provides the access token to the client.

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

  • grant_type: Indicates the authorization type. The value here is fixed to "password", which is required.
  • username: Indicates the username, required.
  • password: Indicates the user's password, required.
  • scope: Indicates the permission scope, optional.

Below is an example.


     POST /token HTTP/1.1
     Host: server.example.com
     Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
     Content-Type: application/x-www-form-urlencoded

     grant_type=password&username=johndoe&password=A3ddj3w

In step C, the authentication server sends an access token to the client, the following is an example.


     HTTP/1.1 200 OK
     Content-Type: application/json;charset=UTF-8
     Cache-Control: no-store
     Pragma: no-cache

     {
       "access_token":"2YotnFZFEjr1zCsicMWpAA",
       "token_type":"example",
       "expires_in":3600,
       "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
       "example_parameter":"example_value"
     }

In the above code, please refer to the section "Authorization Code Mode" for the meaning of each parameter.

During the whole process, the client must not save the user's password.

client mode

Client mode (Client Credentials Grant) means that the client authenticates to the "service provider" in its own name, not in the name of the user. Strictly speaking, the client mode is not part of the problem that the OAuth framework is designed 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.

client mode

Its steps are as follows:

(A) The client authenticates to the authentication server and asks for an access token.

(B) After the authentication server confirms that it is correct, it provides the access token to the client.

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

  • grant_type: Indicates the authorization type. The value here is fixed to "client_credentials", which is required.
  • scope: Indicates the permission scope, optional.

     POST /token HTTP/1.1
     Host: server.example.com
     Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
     Content-Type: application/x-www-form-urlencoded

     grant_type=client_credentials

The authentication server must verify the client's identity in some way.

In step B, the authentication server sends an access token to the client, the following is an example.


     HTTP/1.1 200 OK
     Content-Type: application/json;charset=UTF-8
     Cache-Control: no-store
     Pragma: no-cache

     {
       "access_token":"2YotnFZFEjr1zCsicMWpAA",
       "token_type":"example",
       "expires_in":3600,
       "example_parameter":"example_value"
     }

In the above code, please refer to the section "Authorization Code Mode" for the meaning of each parameter.

update token

If the client's "access token" has expired when the user accesses, you need to use the "update token" to apply for a new access token.

The client issues an HTTP request to update the token with the following parameters:

  • grant_type: Indicates the authorization mode used. The value here is fixed to "refresh_token", which is required.
  • refresh_token: Indicates the update token received earlier, required.
  • scope: Indicates the authorization scope of the application, which cannot exceed the scope of the previous application. If this parameter is omitted, it means that it is the same as the previous application.

Below is an example.


     POST /token HTTP/1.1
     Host: server.example.com
     Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
     Content-Type: application/x-www-form-urlencoded

     grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326440209&siteId=291194637