OAuth2

Time:2020-6-30

Why need oaut2?

Suppose there is a “cloud notes” product, which provides “cloud note service” and “cloud photo album service”. At this time, users need to access these “resources” (notes, pictures) on different devices (PC, Android, iPhone, TV, watch)

So how can users access their own resources? At this time, the traditional way is to provide our “cloud notes” with our own account and password. After successful login, we can obtain resources. However, such an approach will have the following problems:

  • “Cloud note service” and “cloud photo album service” will be deployed separately. Do we need to log in separately?
  • If a third-party application wants to access our “cloud notes”, do you need users to provide accounts and passwords to the third-party applications, so that they can record and then access our resources?
  • How can users limit the authorization scope and service life of third-party applications in our cloud notes? Is it possible to permanently expose all information to it?
  • If the user changes the password and withdraws the authority, all third-party applications will be invalid
  • As long as there is an access to the third-party application is cracked, then the user’s password will be leaked, the consequences are unimaginable.

In order to solve the above problems, oaut2 is applied

What is oaut2?

OAuth (open authorization) is an open standard, which allows users to authorize third-party mobile applications to access the information they store on other service providers without providing the user name and password to the third-party mobile applications or sharing all the contents of their data. Oauth2.0 is the continuation of OAuth protocol, but it is not backward compatible with OAuth 1.0, which completely abolished oauth1.0.

The standard of OAuth 2.0 is RFC 6749. This file first explains that OAuth introduces an authorization layer to separate two different roles: client and resource owner. … with the consent of the resource owner, the resource server can issue a token to the client. The client requests data through token.The core of OAuth is to issue tokens to third-party applications.

Explanation of nouns in oauthor’s rule 2

  • Third party application: also known as client, such as the devices mentioned in the previous section (PC, Android, iPhone, TV, watch), we will install our own app in these devices. For example, our products want to use QQ, wechat and other third-party login. For our products, QQ and wechat login are third-party login systems. We also need the resources (avatar, nickname, etc.) of the third-party login system. For QQ, wechat and other systems, we are third-party applications.
  • HTTP service provider (HTTP service): our cloud note products, QQ and wechat can be called “service providers”.
  • Resource owner: also known as user.
  • User agentThese users, for example, visit resources instead.
  • Authorization server: that is, the server specially used by the service provider to process authentication. In short, it is the login function (verifying whether the user’s account and password are correct and assigning the corresponding permissions)
  • Resource server: the server where the service provider stores the user generated resources. It can be the same server as the authentication server, or it can be a different server. Simply speaking, it is the resource access portal. For example, the “cloud note service” and “cloud photo album service” mentioned in the previous section can be called resource servers.

The operation of oaut2 rule

OAuth2

(A) After the user opens the client, the client requests authorization from the user.

(B) The user agrees to authorize the client.

(C) The client uses the authorization obtained in the previous step to request a token from the authentication server.

(D) After the authentication server authenticates the client, it confirms that it is correct and agrees to issue the token.

(E) The client uses a token to apply to the resource server to obtain resources.

(F) The resource server confirms that the token is correct and agrees to open the resource to the client.

Client authorization mode of oaut2 rule

  • Authorization code

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

    (B) The user chooses whether to grant the client authorization.

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

    (D) The client receives the authorization code and attaches the previous “redirection URI” to apply for a token from the authentication server. This step is done on the background server of the client and is invisible to the user.

    (E) The authentication server checks the authorization code and redirection URI, and sends access token and refresh token to the client after confirmation.

  • Implicit

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

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

    (C) Assuming that the user is authorized, the authentication server directs the user to the “redirection URI” specified by the client and contains an access token in the hash part of the URI.

    (D) The browser sends 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 that contains code to get the token in the hash value.

    (F) The browser executes the script obtained in the previous step and extracts the token.

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

  • Resource owner password credentials

    (A) The user provides the user name and password to the client.

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

    (C) The authentication server provides access token to the client after confirmation.

  • Client credentials

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

    (B) The authentication server provides access token to the client after confirmation.

Detailed steps of authorization code mode of oaut2 client

Authorization code is the most complete and rigorous authorization mode. Its characteristic is to interact with the authentication server of “service provider” through the background server of the client.

(A)The user accesses the client, and the latter directs the former to the authentication server. 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 as “code”
client_ ID: indicates the ID of the client, required
redirect_ Uri: indicates the redirection URI, optional
Scope: indicates the permission range of the application, optional
State: indicates the current state of the client. Any string will be returned intact by the authentication server. It is also used to prevent cross site request forgery attacks. Required

eg:
    GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
    &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1

(B)The user chooses whether to grant the client authorization.

(C)Assuming that the user gives authorization, the authentication server directs the user to the “redirection URI” specified by the client in advance, and an authorization code is attached;
The server responds to the URI of the client, including the following parameters:

Code: indicates authorization code, required. The validity period of the code should be very short, usually set to 10 minutes. The client can only use the code once, otherwise it will be rejected by the authorization server. The code is one-to-one correspondence with client ID and redirection URI.
As like as two peas: State: if the client’s request contains this parameter, the authentication server’s response must be exactly the same.

eg:
    Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz

(D)The client receives the authorization code and attaches the previous “redirection URI” to apply for a token from the authentication server. This step is completed on the background server of the client and is invisible to the user. The HTTP request for a token from the client to the authentication server contains the following parameters:

grant_ Type: indicates the authorization mode used, required. The value here is fixed as “authorization”_ code”。
Code: indicates the authorization code obtained in the previous step, required.
redirect_ Uri: indicates the URL in the redirection URI application. It is used to send users after authorization. It is required and must be consistent with the parameter value in step A.
client_ ID: indicates the client ID of the application, required
client_ Secrect: indicates the client secret of the application, that is, the access resource permission, required

eg:
    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

(E)After checking the authorization code and redirection URI, the authentication server sends an access token and a refresh token to the client. The HTTP reply sent by the authentication server includes 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 a bearer type or a Mac type.
expires_ In: indicates the expiration time, in seconds. If you omit this parameter, you must set the expiration time in other ways.
refresh_ Token: indicates the update token, which is used to obtain the next access token. Optional.
Scope: indicates the scope of permission. If it is consistent with the scope applied by the client, this item can be omitted.

eg:
    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"
    }
    

The flow chart is as follows

OAuth2

Update token

The validity of the token is up. If the user is asked to go through the above process again and apply for a new token, it is likely that the experience will not be good and it is unnecessary. OAuth 2.0 allows users to automatically update tokens.

The specific method is that when the resource server issues a token, it issues two tokens at a time. One is used to obtain data and the other is used to obtain a new token (refresh token field). Before the token expires, the user uses the refresh token to send a request to update the token.

    https://b.com/oauth/token?
        grant_type=refresh_token&
        client_id=CLIENT_ID&
        client_secret=CLIENT_SECRET&
        refresh_token=REFRESH_TOKEN

URL, grant_The type parameter is refresh_Token indicates that the token is required to be updated, client_ID parameter and client_The secret parameter is used to confirm the identity. Refresh_The token parameter is the token used to update the token. After the resource server is verified, a new token is issued.

Comparison of four ways of oaut2

Resource owner password credentials

  • This mode is the least recommended because the client may have stored the user password
  • This mode is mainly used to upgrade legacy projects to oauth2
  • Of course, if the client is a home application, it can
  • Support refresh token

Authorization code

  • This mode is the authentic authorization mode of oauth2
  • The auth code is designed, and the token can be obtained through this code
  • Support refresh token

Implicit

  • This mode has fewer code links than authorization code mode, and callback URL directly carries token
  • The usage scenarios of this mode are browser based applications
  • This mode is based on security considerations, and it is recommended to set the token aging shorter
  • Refresh token is not supported

Client credentials

  • In this mode, the token can be obtained directly according to the client’s ID and key without the user’s participation
  • This mode is more suitable for consuming API back-end services, such as pulling a group of user information
  • Refresh token is not supported, mainly unnecessary

    The original intention of the refresh token is mainly for the user experience, and the user does not want to repeatedly enter the account password to exchange for a new token, so the refresh token is designed to exchange for a new token

    Because there is no user involved in this mode, and the user account password is not required, the new token can be exchanged only according to its own ID and key, so there is no need to refresh the token

safety problem

  1. redirect_uri

    Q: why does OAuth 2.0 require an applicationclient_idYou must enter a domain name and requestredirect_uriMust be an address under this domain name?

    A: if others know about usclient_idAnd then, in the second part of the generation of authorization connection, set theredirect_uriReplace it with the one under your domain name and you will get itcodeAnd stored in their own server

  2. code

    IfThird party servicesIf you do not support HTTPS, you will be hijacked. withoutcode, but directly backaccess_tokenstayredirect_uriThe middleman can use it directlyaccess_token

  3. app_secret

    IfcodeObtained by a middleman, in the absence ofapp_secretIt can be used directlycodeexchange foraccess_token。 Because in the whole acquisitioncodeIt’s all exposed

  4. state

    stateParameters, if used, are treated asCSRF TokenThis can be avoided:

    1. The attacker still gets the code and intends to trick the victim into clicking
    2. The victim clicks on the link, but due to the server (e.g chrisyue.com )The state value of the device assigned to the victim is different from the state value in the link( chrisyue.com )Failed to directly return to verify state
`As long as the random string "state" or "CSRF token" is bound to a device, as long as it is slightly more complicated, it is impossible for the attacker to guess. Setting a value of state (CSRF token) bound to the device or browser that the attacker can't guess is the key to solve the CSRF attack.

Summary of oaut2 implementation process

The implementation mechanism of auth2 is that different clients need to request access to the resource server_Token) to obtain different resources, The server needs to verify whether the client is registered with the resource server, and what is the access rights of the resource server to which the client is assigned. Therefore, the user needs to be redirected to the authentication server by the client to verify its identity. If the authentication is passed, a code code code that can only be used once to obtain the token is returned as the request t When the client requests token, it must also pass a required parameter client that needs to obtain the resource permission_Secrect, and the parameter client_ID (the identity of the client). If the authentication is passed, the client obtains the resource and displays it to the user.

reference material:
https://www.jianshu.com/p/a7d…
http://www.ruanyifeng.com/blo…
http://www.ruanyifeng.com/blo…
http://www.ruanyifeng.com/blo…
https://developer.github.com/…
https://www.jianshu.com/p/7b1…