1. Introduction

A book tour on weekends, Read a wonderful article, Click big red heart to like, Just jump to the login interface, You need to log in to like.




But no, I don't have a profile account, Always usedQQ Integrated login for. There is a row of social login buttons below, We can log in with a third-party social account. clickQQ Icon, I'll jump toQQ Login authorization page, Following chart:




From the picture, we can see that there are two parts, One is the user on the left, One is to tell Jianshu on the right what authority it will obtain. inputQQ Account and password, Click authorize and log in, Then I successfully log in to Jianshu, And succeeded in getting meQQ Account and nickname of, Following chart:



Social login integrated with simple books, Greatly simplifies our registration and login process, It's really No.1 Online.
This seems like a simple integration, But the technology behind it『OAuth2.0』 It's not that simple, Then we don't talk much, Let's find out.

2. OAuth 2.0

OAuth 2.0 <https://oauth.net/2/> Is an industry standard agreement for licensing.OAuth
2.0 Instead of2006 Original created inOAuth Work done on the agreement.OAuth
2.0 Focus on client developer simplicity, Also forWeb application program, Desktop applications, Mobile phone and living room equipment provide specific authorization process.

In traditionalclient-server In the authentication model, Client requests access to restricted resources on server(protected
resource), Need to use resource owner(resource
owner) Credentials for are authenticated on the server. To support third-party application access to restricted resources, Resource owners need to apply shared credentials to third parties. This causes the following problems:

* Third party applications for subsequent use, The credentials of resource owners are stored, mainly passwords.
* The server needs to support password authentication, Although password authentication is not secure.
* Third party applications gain excessive access to resources rather than limited resources, And the resource owner has no way to restrict it.
* Resource owner cannot revoke permission, Unless you change the password.
* If the password of the third party application is cracked, All data protected by this password will be leaked.

Think about a scene like this, If the short book is used directlyQQ User name password login, It's very likely that Jane's book will be kept for subsequent business needsQQ User name and password, As long as Jane has the bookQQ User name and password can access more thanQQ Nickname? Head portrait and other information, You can even getQQ All address book lists for users. If the account and password of Jianshu are disclosed, It will directly affectQQ Data security. This is a terrible problem.

thereforeOAuth Emerge as the times require, To solve this problem.

3. OAuth 2.0 Authorization process

Let's use it as a simple bookQQ Authorized login as an example, Let's take a stroll.OAuth 2.0 Process.
First look at it.OAuth 2.0 Process, As shown in the figure below:


There are four main roles in it:

* Client: Clients requiring authorization, In this paper【 Brief book】.
* Resource Owner: Resource owner, In this article, you might think it's QQ, But think about it,QQ It's personal, So in this paper, resource owner means【QQ user】.
* Authorization Server: Authentication server, Special reference in this article【QQ Interconnection platform】.
* Resource Server: Resource server, Seeing the name of a thing one thinks of its function, Servers dedicated to saving resources, Accept access through an access token. This article refers specifically to【QQ User information center】.
3.1. First step: Guide users to the authentication server


Saint Jay opens the profile page, Brief book jump to login interface, Require user login. But Saint Jay didn't register his account with Jianshu, So I clickedQQ Icon, UseQQ Account for integrated login. Jump toQQ After login,QQ Require user authorization.
In this step, Jianshu mainly does the following: guide the user to the authentication server.
Obviously【QQ Interconnection platform】 Authentication server.

How to guide? Page Jump, of course.
How does the authentication server know the authentication request from the profile?
Of course, it's Chuanshen.
What parameters do I need to pass?

* response_type: Indicates response type, Necessary option, The value here is fixed to"code";
* client_id: Represents the client'sID, Used to mark the source of authorization request, Necessary option;
* redirect_uri: Callback address after successful authorization;
* scope: Indicates the permission scope of the application, Optional;
* state: Represents the current state of the client, Any value can be specified, The authentication server will return this value intact.
Let's take a look at the authorization request actually sent by the profileUrl yes:
https://graph.qq.com/oauth2.0/authorize?client_id=100410602
&redirect_uri=http://www.jianshu.com/users/auth/qq_connect/callback
&response_type=code &state=bb38108d1aaf567c72da0f1167e87142d0e20cb2bb24ec5a

No plan, no truth, Let's take a look at the network monitoring of the console:



As shown in the figure, exceptscope Parameter outside, The other four parameters have parameters.
At this point, you may only be rightstate Parameters are confusing, Pass astate parameter, The authentication server will return intact, Why do you want to pass it onstate What about parameters??

My understanding is, One for Jane's bookguid Extended string to uniquely identify an authorization request. In this way, the authorization code returned by the authorization server can be obtained correctly.

Here you may ask, Now that I know the parameters, Can't I forge a request for short form certification, modifyredirect_uri Parameter to jump to personal website, And then it's not availableQQ To grant authorization?

It's just as stupid and naive as me, Jane's bookQQ When applying for the Internet platform, it must have reserved the records to jump backURL.QQ When the Internet platform receives the authorization request of the profile, it will definitely verify the callbackUrl Of.

3.2. The second step: User agrees to authorize third party client


This step, For users, Just use the resource owner(QQ) User name password login for, And agree to authorize. After clicking authorize and logging in, The authorization server will firstpost A request goes back to the server for user authentication, After the authentication is passed, the authorization server will generate an authorization code, The server then requests
redirect_uri Jump, And return the authorization codecode And thestate.
What we should pay attention to here is: The authorization code has a short time limit

No plan, no truth, Let's take a look at the console network monitoring:



From the diagram, we can verify what we said above, Finally jump back to the simple bookUrl by:

http://www.jianshu.com/users/auth/qq_connect/callback?code=093B9307E38DC5A2C3AD147B150F2AB3
&state=bb38108d1aaf567c72da0f1167e87142d0e20cb2bb24ec5a
And previous authorization requestsURL Contrast, Can be foundredirect_uri,state Completely consistent.
andcode=093B9307E38DC5A2C3AD147B150F2AB3 Is the returned authorization code.

3.3. The third step: Use authorization code to request token from authentication server

From here on, Invisible to users. Behind the scenes, Jane is doing the follow-up work silently.

Get the bookQQ After the authorization code returned by the Internet platform, You need to apply for a token again from the authentication server according to the authorization code(access token).
It is necessary to clarify two concepts here:

* Authorization code(Authorization Code): It is equivalent to the oral briefing of authorized server, User agrees to authorize his useQQ I've logged in to Jianshu.
* token(Access Token): Equivalent to temporary ID card.
How to apply for a token?
Jane needs to send aget Request to authentication server(QQ Interconnection platform).
What is the necessary information to carry?
Yes, To carry the following parameters:

* grant_type: Indicates authorization type, The value here is fixed to"authorization_code", Necessary option;
* client_id: Express fromQQ Clients applied by Internet platformID, Used to flag the source of the request, Necessary option;
* client_secret: This is fromQQ Client authentication key applied by Internet platform, Confidential information is very important, Necessary option;
* redirect_uri: Callback address after successfully applying to token;
* code: Authorization code applied in the previous step.
According to the above information, we can simulate an applicationAccessToken Request:
https://graph.qq.com/oauth2.0/token?client_id=100410602
&client_secret=123456jianshu
&redirect_uri=http://www.jianshu.com/users/auth/qq_connect/callback
&grant_type=authorization_code &code=093B9307E38DC5A2C3AD147B150F2AB3

After sending the request, After the authentication server passes the verification, the token will be issued, And return to Jianshu backstage, It should contain the following information:

* access_token: token
* expires_in:access token Validity period, The unit is seconds..
* refresh_token: In the authorization auto renewal step, Get newAccess_Token Parameters to be provided when.
same, We can simulate a returntoken:

http://www.jianshu.com/users/auth/qq_connect/callback?access_token=548ADF2D5E1C5E88H4JH15FKUN51F
&expires_in=36000&refresh_token=53AD68JH834HHJF9J349FJADF3

At this time, Jane book has another thing to do, It's about putting userstoken write tocookie in, Maintain user login status. Let's turn on the controller and verify.



It can be seen from the figure that the usertoken Save in theremember_user_token Ofcookie in.
No need to fight.cookie It's a bad idea, It must be encrypted.
You can try the manualremember_user_token This articlecookie delete, Ensure that you need to log in the profile again after refreshing the interface.

3.4. The fourth step: Request resources from resource server

Yes.token, Send a to the resource interface provided by the resource serverget Please don't do it, The resource server verifies that the token is correct, It will return resources to Jianshu(QQ User information).

Let's also simulate a usetoken requestQQ User basic information resourcesURL:
https://graph.qq.com/user/get_user_info?client_id=100410602 &qq=2098769873
&access_token=548ADF2D5E1C5E88H4JH15FKUN51F

To this stepOAuth2.0 It's over, But there are still important things to do for Jane's book. That is:
Gettoken,reresh_token It's silly not to save such important things as user data?

3.5. The fifth step: Token extension( Refresh)

You must have returned to step fourrefresh_token More curious.
It is used to delay the token( Refresh) Of. Why are there two ways of saying it, Because it is possible that the authentication server will regenerate a token, It is also possible.
Delay expired tokens.

For instance,QQ Internet platform for security, Returnedaccess_token There's a time limit, What if the user doesn't want to authorize one day, I can't give you oneaccess_token
You can use it in a few years. The validity of the token returned by our above simulation is10 hour.10 Hour later, User opens browser to browse brief books, User's in browsertoken Correspondingcookie Expired. Jianshu finds that the browser is not carriedtoken Information coming, Understandtoken Invalid, Need to re apply for authorization from the certification platform. If the user clicks againQQ Login authorization, This is obviously a bad user experience. Why??
refresh_token
That's where it comes in, You can directly skip the previous steps of applying for authorization code, When foundtoken Invalid, Jane's book from browsercookie Mediumsessionid Find the
refresh_token, Then userefresh_token Conducttoken Renewal( Refresh).

That userefresh_token Conducttoken What do I need to do to renew it?
You also need to send aget request.
What parameters are required?

* grant_type: Indicates authorization type, The value here is fixed to"refresh_token", Necessary option;
* client_id: Express fromQQ Clients applied by Internet platformID, Used to flag the source of the request, Necessary option;
* client_secret: This is fromQQ Client authentication key applied by Internet platform, Confidential information is very important, Necessary option;
* refresh_token: That is, the returnedrefresh_token.
Based on the above information, We can simulate a token refreshURL:
https://graph.qq.com/oauth2.0/token?client_id=100410602
&client_secret=123456jianshu
&redirect_uri=http://www.jianshu.com/users/auth/qq_connect/callback
&grant_type=refresh_token &refresh_token=53AD68JH834HHJF9J349FJADF3
What about the returned results?
Same as the result of step 4.

You may have another question here, So, since every time a token is delayed, it will return onerefresh_token, Can't I use itrefresh_token Unlimited delay?
Naive as me,refresh_token It also has expiration time. The expiration time is determined by the authentication server.
generally speakingrefresh_token Expiration time of is greater thanaccess_token Expiration time of. Only in this way,access_token Expired, Can be used
refresh_token Extend token( Refresh).

A simple example:
Suppose that JianshuQQ Obtained by default from the Internet platformaccess_token Is valid for1 day,refresh_token Valid for one week.

Users use todayQQ After login authorization, After two days, I'll go shopping in Jianshu, Discovery of Jian Shutoken Invalid, Use immediatelyrefresh_token refresh token, Silently completed the extension of authorization.
If the user goes shopping for a short book every two weeks, Brief book one check,access_token,refresh_token
All failed, You can only guide the user to the authorization page to reauthorize, That is, back toOAuth2.0 First step.

4.0 summary

This article passes by the simple bookQQ For example, authorized login, YesOAuth2.0 The authorization process of, Hope to read through this article, Help you.

If yesOAuth2.0 What you know, You should understand that this article is actually rightOAuth2.0 Explanation of authorization mode of authorization code mode in.

If you want to knowOAuth2.0 Other ways of authorization, Recommended for referenceOAuth 2.0 - Ruan Yifeng's Weblog
<http://www.baidu.com/link?url=j4_T_fCI4T_gWL2Snyg_xg9DfuYvjKupGPbyr6HnHRJRlpEFAUMPaIEUgszkDxfKUbf_r-dRmYYaFXm13C-BEK>
.