First published at: github.com/USTB-musion…

Writing in the front

Yesterday, I shared the third party login and single sign-on in the group, especially the oAuth2 protocol in the third party login, which is recorded and sorted out here. OAuth protocol is an open network standard for authorization. It is mainly used to solve third-party login. The so-called third-party login is actually the authorization of oAuth.

What is third-party login

Many websites allow users to log in using the identity of a third-party website. This is called “third-party login”. Such as Zhihu and MOOCs, you can use wechat, QQ or Weibo to log in. If a website wants to access the third party login, it needs to use oAuth protocol.

What is the request

OAuth is an open web standard for authorizing third-party applications to access user data. Its ultimate purpose is to issue a time-sensitive access_token to the third-party application, according to which the third-party application can obtain relevant resources of the user, such as avatar, nickname, email and other information. The current version is basically version 2.0.

The oAuth2.0 protocol is based on the article RFC 6749. For more comprehensive information, you can visit 👆. Here are the roles and processes of oAuth2.

The agreement process

Before going into the details of the oAuth2 protocol process, let’s take a quick look at a few roles for subsequent understanding.

  • Resource Owner: the Owner of a Resource is the user who requests information about the user’s avatar and nickname.
  • Client, such as a Web site or app
  • Resource Server, a Server that hosts protected resources
  • The Authorization Server is generally an application of the same company as the resource Server. It is mainly used to process Authorization and issue tokens to clients
  • User-agent is a User agent, usually a Web browser, or app on a mobile phone

With these roles in mind, take a look at how oAuth2.0 works.

+--------+ +---------------+ | |--(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

(A). The user opens the Client, and the Client sends an authorization request to the Resource Owner

(B). The user agrees to authorize the Client

(C). The client uses the Authorization Server for authentication

(D). After passing the authentication, the authentication server will issue the Access Token to the client.

(E). The client holds the Access Token and applies to the Resource Server for obtaining resources

(F). After the Resource server confirms the token, it returns the Protected Resource to the client.

Authorization way

In oAuth2, four authorization methods are defined for different business scenarios:

  • The authorization Code mode is the most complete and rigorous authorization mode. It is used jointly by the server and the client, mainly for Web servers
  • Simplified patterns (implicit) : Used primarily for mobile applications or pure front-end Web applications, with no Web server
  • Resource Owner password Credentials: This mode is not recommended. Users need to provide their own accounts and passwords to clients, which are also allowed if the clients are their own applications
  • Client credentials: Clients authenticate to service providers in their own names instead of the users’ names. For example, wechat public accounts use the Access_token to access the information of all users they care about, and Docker images are retrieved from dockerHub

Authorization code mode

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

Note: The lines illustrating steps (A), (B), and (C) are broken into two parts as they pass through the user-agent.

The authorization code mode is shown in the figure above. This authorization mode is the most complete and rigorous authorization mode, and is suitable for Web applications with a back end. It is characterized by communication between the background server of the client and the authentication server of the service provider. Here’s how it works if I want to use Github to access third-party logins:

(A). If the User (Resource Owner) selects A third-party application (such as Github) on the User Agent (such as Web browser or app) to log in, the User will be redirected to the authorization endpoint of Github:

The payload = https://github.com/login/oauth/authorize? code & client_id = your_code & redirect_uri = redirect url & scope = read & state=uuidCopy the code
field describe
response_type Yes, this parameter is fixed to code in authorization code mode
client_id This must uniquely identify the client ID obtained during github registration
redirect_url The client registers a redirect URL on Github. Users are redirected to this REDIRECT URL when they agree or reject the redirect url
scope This parameter is optional. If multiple resources are requested, separate them with multiple Spaces
state It is recommended that the resource server return random numbers generated by the client as they are to prevent CSRF attacks

(B). After the page jumps, Github will ask the user to log in, and then ask whether to authorize the client, and the user clicks “agree”.

(C). Github then returns the Authorization Code to the redirect_URI.

redirect_uri? code=xxxxxxxCopy the code
field describe
code Yes, the authorization code
state Parameters to prevent CSRF attacks

(D). After fetching the authorization code from the URL, the Client can request the token from Github at the back end

https://github.com/login/oauth/access_token? client_id=your_code& client_secret=your_secret& Grant_type = authorization_code&code = Fetched code&redirect_uri = REdirected URLCopy the code
field describe
client_id Yes, the unique identifier of the client registered on Github
client_secret Yes, the key returned by the client when registering with Github
grant_type Must, authorization_code/refresh_code
code Yes, the authorization code retrieved in the previous step
redirect_uri Yes, the callback address after authorization is the same as when you registered on Github

(E). Github returns AccessToken to the address specified by redirect_URI in JSON format

{
  "access_token":"xxxxxxx",
  "token_type":"bearer",
  "expires_in":3600,
  "refresh_token":"xxxxxxx"
}
Copy the code

The client can retrieve the access_token at the back end. In this JSON, it also returns a refresh_token, which indicates that the refresh_token is used to access the update token for the next time. The refresh_token is longer than the access_token. When an Access_Token expires, refresh_Token can be used to exchange for a new access_token.

Simplify the model

The simplified mode is mainly aimed at pure front-end applications without a back end. In this case, the process of authorization code mode cannot be adopted because there is no back end. The Access_token must be stored in the front end.

+----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ Client Identifier +---------------+ | -+----(A)-- & Redirection URI --->| | | User- | | Authorization | | Agent -|----(B)-- User authenticates -->| Server | |  | | | | |<---(C)--- Redirection URI ----<| | | | with Access Token +---------------+ | | in Fragment | | +---------------+ | |----(D)--- Redirection URI ---->| Web-Hosted | | | without Fragment | Client | | | | Resource | | (F) |<---(E)------- Script ---------<| | | | +---------------+ +-|--------+ | | (A) (G) Access Token | | ^ v +---------+  | | | Client | | | +---------+Copy the code

Note: The lines illustrating steps (A) and (B) are broken into two parts as they pass through the user-agent.

Mainly in step B, the page is redirected to Github and the user agrees to authorize the client. Github takes the token as the URL parameter and jumps back to the callback address of redirect_URI.

Callback address #token= XXXXXXCopy the code

Note that the token is in a FRAGMENT of a URL, not a querystring. This is because OAuth 2.0 allows URL hops to HTTP, so there is a risk of “manin the middle” attacks. When the browser hops, the anchor will not be sent to the server. The risk of token leakage is reduced.

Password mode

RFC 6749 also allows users to give a user name and password directly to an application if you have high trust in it. The app uses your password to request a token, which is called “password”.

+----------+
 | Resource |
 |  Owner   |
 |          |
 +----------+
      v
      |    Resource Owner
     (A) Password Credentials
      |
      v
 +---------+                                  +---------------+
 |         |>--(B)---- Resource Owner ------->|               |
 |         |         Password Credentials     | Authorization |
 | Client  |                                  |     Server    |
 |         |<--(C)---- Access Token ---------<|               |
 |         |    (w/ Optional Refresh Token)   |               |
 +---------+                                  +---------------+

        Figure 5: Resource Owner Password Credentials Flow
Copy the code

The password mode is that the user provides his account number and password to the client, and the client uses this information to ask for authorization from our service provider.

Client mode

The client in its own name, rather than the name of the user, to the “service provider” authentication, such as wechat public number with access_token to pull all the concerned user information, Docker to Dockerhub pull image, etc..

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

                 Figure 6: Client Credentials Flow
Copy the code

The client mode, as the name implies, means that the client uses its own name instead of the user’s name to authenticate the service provider. Strictly speaking, this mode is not the problem that oAuth framework solves. In this client mode, it directly obtains an access_token through the key and ID of the client. No user involvement is required.

Single sign-on (sso)

What about the understanding of oAuth2, about this much content. OAuth protocol is mainly used to solve the third party login, but when talking about the login scheme in different scenarios, in addition to the third party login, there is a concept, that is, single sign-on.

Single sign-on (SSO) means that in multiple systems, a user only needs to log in once, and each system can perceive that the user has logged in. For example, if you log in to Tmall, Taobao will automatically log in. Simply put, single sign-on (SSO) is a process that allows users to log in to multiple products at the same time by taking the user login logic out of two or more products and entering the user name and password only once.

Single sign-on implementation scheme

The first is single sign-on in the same parent domain, such as hr.oa.com, km.oa.com, fuli.oa.com. In this case, cookies can be shared by setting the domain property to the secondary domain oa.com, and then the server can realize single sign-on by sharing the session. In addition to sharing sessions, you can also use JWT.

The second is for single sign-on under different domains, such as Taobao and Tmall, its secondary domain name is not the same. In this case, you have to solve the problem of cookies not being shared. Now the mainstream solution is to use CAS to achieve.

conclusion

To summarize briefly, the main login solutions for different business scenarios, the first is the single sign-on solution for the same company under the same parent domain. In this case, because cookies are under the same parent domain, cookie sharing can be realized by setting the domain attribute of cookies. The server session sharing can then implement single sign-on (SSO). But another solution of this kind is JWT. JWT is a JSON Web token. It is essentially a string consisting of a header, payload, and signature.

The second method is for single sign-on solutions of the same company but in different domains, such as single sign-on of Taobao and Tmall. CAS is the mainstream solution of this method.

The third is different companies, different domains under the use of third-party login function. Such as third-party websites need access to wechat login, QQ login, Weibo login, etc., the implementation of the third-party login function, using the oAuth2.0 protocol just introduced.

Refer to the article

OAuth 2.0 in four ways

You can pay attention to my public account “Muchen classmates”, goose factory code farmers, usually record some trivial bits, technology, life, perception, grow together.