background

Let’s start with a very typical example. Let’s say you upload a lot of your photos to a web disk that provides photo storage, and another print store that provides online printing.

Because storage and promise is provided by two different service providers, both of which provide user registration functions respectively, so if you want to print the photos you put on the web disk in the print shop, at this time you will think of two schemes:

  • Assuming you have different passwords for your accounts, you can download the pictures to be printed from a web disk and then upload them to the print shop’s website. This model is the most primitive and the least efficient.
  • In order to save trouble, you can give your network disk account password to the printing shop owner, tell him you want to print the picture, let him give you operation, save trouble, but the risk is too big, account password is leaked, not afraid of others to tamper with personal information or view your privacy?

Many companies, including Google, Yahoo, and Microsoft, have tried to solve this problem, which led to the birth of OAuth.

What is OAuth?

OAuth (Open Authorization) is an Open standard that allows users to allow third-party applications to access private resources (such as photos, videos, and contact lists) stored by users on a website without providing user names and passwords to third-party websites or sharing all content of their data. At present, it is widely used all over the world.

OAuth solution

OAuth sets an Authorization Layer between the Client (print shop) and the Resource Server (web disk). User Authorization is provided through the Authorization Server.

The client must go through the authorization layer to access the Resource server. The user, namely the Resource Owner, can specify the permission scope and validity period of the authorization layer token when logging in, and open the data stored by the user to the client only after the user agrees to authorize.

Generally speaking: when the print shop wants to access the user’s picture of your web disk, through the OAuth mechanism, the print shop needs to request authorization from the authorization server of the web disk, and the web disk service provider will guide you to log in on the web disk website, and ask you whether to authorize the service of accessing the picture to the print shop. When you click yes, the print shop will have access to the photo service on your web disk. The whole process of printing shop does not touch your network disk account information, safe and convenient.

OAuth authorization process

Abstract Protocol Flow

+--------+ +---------------+ | |--(A)- Authorization Request ->| Resource | | | | Owner | | |<-(B)-- Authorization Grant  ---| | | | +---------------+ | | | | +---------------+ | |--(C)-- Authorization Grant -->| Authorization | | Client | |  Server | | |<-(D)----- Access Token -------| | | | +---------------+ | | | | +---------------+ | |--(E)----- Access Token ------>| Resource | | | | Server | | |<-(F)--- Protected Resource ---| | +--------+ +---------------+Copy the code

The general process is as follows:

  • Authrization Request: The user opens the client, and the client requests the user to access the resource serverauthorization grant, requires authorization from the user.
  • Authorization Grant (Get): The user agrees to the authorization request, and the client receives oneauthorization grantLicensing.
  • Authorization Grant (Post): The client sends its own client identity to the authorization server as well as in the previous stepauthorization grantGrant permission, request access token.
  • Access Token (Get): The authentication server authenticates the client. If the authentication succeeds andauthorization grantAlso authenticated, the authorization server will be distributed to the clientaccess tokenAccess the token, and the authorization phase is now complete.
  • Access Token (Post && Validate): The client sends a message to the resource serveraccess tokenUsed to validate and request resource information.
  • Protected Resource (Get): The resource server performs request validation ifaccess tokenIf the authentication succeeds, the resource server returns the resource information to the client.

Authorization model

OAuth 2 defines four Grant types based on how applications request authorization and the Grant types supported by the licensor service, each of which has its own application scenarios:

  • Authorization Code Mode (Authorization Code) : The most commonly used type of license, used in conjunction with normal server-side applications.
  • Implicit authorization mode (Implicit) : Skip the authorization code step for mobile applications orWeb App
  • Password mode (Resource Owner Password Credentials) : The client provides the account password and requests authorization from the service provider. This is applicable to trusted client applications
  • Client mode (Client Credentials) : The client directly requests authorization from the service provider, which is applicable for the client to invoke the main serviceAPIType of application

Authorization Code Mode (Authorization Code)

It is the most commonly used Authorization mode on the Internet at present, such as QQ, Weibo, Facebook and Douban, etc. It requires third-party applications to apply for an Authorization Code, and then use the Code to obtain the token and request data. The process is as follows:

+----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ +---------------+ | -+----(A)-- User Authorization Request ---->| | | User- | | Authorization | | Agent -+----(B)-- User authenticates ------------>| Server | | | | | | -+----(C)-- Authorization Code Grant ------<| | +-|----|---+ +---------------+ | | ^ v (A) (C) | | | | | | ^  v | | +---------+ | | | |>---(D)-- Access Token Request ---------------' | | Client | | | | | | |< ---(E)-- Access Token Grant -----------------------' +---------+ (w/ Optional Refresh Token)Copy the code

User Authorization Request: The User accesses the client. The client constructs a URL to Request Authorization code and directs the User to redirect. The link format is similar to the following:

https://open.server-name.com/oauth2/authorize
    ?response_type=code
    &client_id=AppID
    &redirect_uri=REDIRECT_URI
    &scope=SCOPE
    &state=STATE
Copy the code
  • response_type: Authorization mode. This parameter is mandatorycode
  • client_id: Client id, usually assigned during registrationAppID
  • redirect_uri: Redirection address after authorization. This parameter is mandatoryuriforURLEncode
  • scope: Entitlement scope, optional
  • state: Indicates the client status. This parameter is mandatory. It is a random character stringCSRFattack

User authenticates: The User decides whether to authorize the client. The authorization service prompts the User to authorize or deny the application access to his account information

Authorization Code Grant: When the user confirms Authorization, the Authorization server redirects the redirect_URI address provided by the client, along with the Code and state parameters, and the client can obtain the Authorization Code value. The link format is as follows:

https://client-name.com/redirect_url
 ?code=520DD95263C1CFEA087
 &state=STATE
Copy the code
  • code: Generated by the authorization serverauthorization code, the authorization code,codeThe period of validity is short and generally maintained at5-10Minutes: The authorization server can be configured by itself
  • state: is carried by the client beforestateValue can be checked to prevent matching with the initial set of status valuesCSRFattack

Access Token Request: After obtaining the authorization code, the client can Request the server to obtain the access_token. Generally, the Request parameters are as follows:

parameter Whether must meaning
grant_type Must be Authorization type. This value is fixed asauthorization_code
code Must be Authorization code
client_id Must be Client id, usually assigned by a third partyAppID
client_secret Must be The client key is usually assigned by a third partyAppSecret
redirect_uri Must be Callback address, and the previousredirect_uriconsistent

Access Token Grant: The server verifies the parameters sent by the client and returns the Access Token to the client after the authentication is successful. Generally, the data returned is as follows:

{
  "access_token":"2YotnFZFEjr1zCsicMWpAA"."token_type":"example"."expires_in": 3600,"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"."scope":"user_info"
}
Copy the code
  • access_token: Access token
  • token_type: token type
  • expires_in: token expiration time
  • refresh_token: Refresh the token
  • scope: Scope of permission

Refresh_token is used to obtain a new Access_Token in the automatic authorization renewal step.

At this point, the authorization process is complete.

Implicit authorization mode (Implicit)

The Authorization Code pattern is very similar to the previous Authorization Code pattern, except that the Authorization Code is omitted and the access token and optional refresh token are returned directly. This applies to third-party applications that do not have a Server Server to process Authorization codes. The entire process is as follows:

 +----------+
 | Resource |
 |  Owner   |
 |          |
 +----------+
      ^
      |
     (B)
 +----|-----+                                         +---------------+
 |         -+----(A)-- User Authorization Request --->|               |
 |  User-   |                                         | Authorization |
 |  Agent  -|----(B)-- User Authenticates ----------->|     Server    |
 |          |                                         |               |
 |          |<---(C)-- Redirect URI With ------------<|               |
 |          |          Access Token                   +---------------+
 |          |            
 |          |                                         +---------------+
 |          |----(D)---Follow  Redirect URI --------->|   Web-Hosted  |
 |          |                                         |     Client    |
 |          |                                         |    Resource   |
 |          |<---(E)-- Send Token Extract Script ----<|               |
 |          |                                         +---------------+
 +-|--------+
   |    |
  (A)  (F) Pass Token to Application
   |    |
   ^    v
 +---------+
 |         |
 |  Client |
 |         |
Copy the code

User Authorization Request: The client constructs a link to Request Authorization in the following format:

https://open.server-name.com/oauth2/authorize
    ?response_type=token
    &client_id=AppID
    &redirect_uri=REDIRECT_URI
    &scope=SCOPE
    &state=STATE
Copy the code

Compared to the previous authorization code pattern, only response_type is replaced with token

User Authenticates: As before, the User decides whether to authorize the client

Redirect URI With Access Token: The authentication server redirects the user to the redirect_URI specified by the client and adds an Access Token to the URI. The link format is as follows:

http://client.name.com/redirect_url/#access_token=2YotnFZFEjr1zCsicMWpAA&token_type=Bearer&expires_in=3600&scope=SCOPE&state=STATE
Copy the code

At this time, token_type has been Bearer.

Note that the return value is placed in the hash part of the REDIRECT_URI, not as? Query parameter so that the browser does not send the data to the server when accessing the URL specified by the redirect.

Follow Redirect URI: Indicates the client address identified by the redirect_URI requested by the browser. This address does not contain the hash value and retains access_token information.

Send Token Extract Script: The client returns a page containing the Token, and the page executes a Script to obtain the access_token in the redirect_URI.

Pass Token to Application: the browser obtains the Token and sends it to the client.

At this point, the authorization process is complete.

Password mode (Resource Owner Password Credentials)

In this mode, the client directly uses the username and password provided by the user to request access_token information. This mode is generally applicable to the situation where the user highly trusts the third-party client. The whole process is as follows:

+----------+ | Resource | | Owner | | | +----------+ v | (A) Resource Owner Password Credentials From User Input | v +---------+ +---------------+ | |>--(B)---- Resource Owner ----------------->| | | | Password Credentials To Server | Authorization | | Client | | Server | | |<--(C)- Access Token Passed To Application-<| | | | (w/ Optional Refresh Token)  | | +---------+ +---------------+Copy the code

Resource Owner Password Credentials From User Input: The User provides the User name and Password as the authorization Credentials to the client.

Resource Owner Password Credentials From Client To Server: The client sends the authorization credentials entered by the user to the authorization server to request access token(the client must have been registered on the server). The request parameters are as follows:

parameter Whether must meaning
grant_type Must be Authorization type. This value is fixed aspassword
username Must be User login name
passward Must be User login password
scope Not a must Scope of authorization

Access Token Passed To Application: The authorization server authenticates the client and verifies the validity of the user credentials. If the authentication passes, the Access Token is returned To the client.

At this point, the authorization process ends.

Client mode (Client Credentials)

This is the simplest authorization mode. The client directly initiates authorization from the authorization server in its own name instead of the user’s name to obtain the access_token. The process is also very simple:

 +---------+                                  +---------------+
 |         |                                  |               |
 |         |>--(A)- Client Authentication --->| Authorization |
 | Client  |                                  |     Server    |
 |         |<--(B)---- Access Token ---------<|               |
 |         |                                  |               |
 +---------+                                  +---------------+
Copy the code

Client Authentication: The Client initiates authorization requests directly. The value of grant_type is client_credentials

Access Token: After the authentication server confirms the identity, it issues an Access_token to the client

A profound

As Authorization Code mode is currently the most widely used Authorization mode with the most complete and rigorous procedures, I take koA2 as an example to customize a simple Authorization Code Authorization scheme.

The main idea is to guide the user to click on the authorization page through the client. After confirming the authorization on the authorization page, the user requests the code from the back end, redirects to the redirect_URI, and obtains the code from the server end. After that, code is used to request the server to obtain the token access_token, and then the user information is obtained by access_token. The overall effect is as shown in the figure below:

Here I will not put the code, easy to occupy space!! Please click here for details

Pass: all the data in the code is mock, or there are many exception cases that are not processed, so as to understand the whole authorization process and implementation ideas, just for reference

conclusion

OAuth’s authorization scheme is now very mature, and it is also very common in the entire Internet industry. It was first contacted when I did the wechat ecological public account in the early years, and now I have an in-depth understanding of it, which is also some progress.

I hope that after reading this article, you can also have a deep and comprehensive understanding of OAuth authorization, or deepen and consolidate the knowledge of OAuth authorization.

Combining theory with practice is what we should pursue as coder. Come on!

References and literature

  • The OAuth 2.0 Authorization Framework
  • An Introduction to OAuth 2
  • OAuth2 authorization
  • Understand the 2.0