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 used QQ Integrated login for . There is a row of social login buttons below , We can log in with a third-party social account . click QQ Icon , I'll jump to QQ Login authorization page , As shown below :




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 she will obtain . input QQ Account and password , Click authorize and log in , Then I successfully log in to Jianshu , And succeeded in getting me QQ Account and nickname of , As shown below :



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 Replaced in 2006 Original created in OAuth Work done on the agreement .OAuth
2.0 Focus on client developer simplicity , At the same time Web application program , Desktop applications , Mobile phone and living room equipment provide specific authorization process .

In the traditional client-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 directly QQ User name password login , It's very likely that Jane's book will be kept for subsequent business needs QQ User name and password , As long as Jane has the book QQ User name and password can access more than QQ Nickname? , Head portrait and other information , You can even get QQ All address book lists for users . If the account and password of Jianshu are disclosed , It will directly affect QQ Data security . This is a terrible problem .

therefore OAuth emerge as the times require , To solve this problem .

3. OAuth 2.0 Authorization process

Let's use it as a simple book QQ Authorized login as an example , Let's have a stroke OAuth 2.0 Process of .
Let's see first OAuth 2.0 Process of , As shown in the figure below :


There are four main roles in it :

* Client: Clients requiring authorization , In this paper 【 A 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 Internet 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 specifically refers to 【QQ User information center 】.
3.1. Step 1 : 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 clicked QQ Icon , use QQ Account for integrated login . Jump to QQ After login ,QQ Require user authorization .
In this step, Jianshu mainly does the following: guide the user to the authentication server .
Obviously 【QQ Internet 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 , Required , The value here is fixed to "code";
* client_id: Represents the client's ID, Used to mark the source of authorization request , Required ;
* 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 profile Url 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 , except scope Out of parameters , The other four parameters have parameters .
At this point, you may only be right state Parameters are confusing , Pass a state parameter , The authentication server will return intact , Why do you want to pass it on state Parameters ?

My understanding is , One for Jane's book guid 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 , modify redirect_uri Parameter to jump to personal website , And then it's not available QQ to grant authorization ?

It's just as stupid and naive as me , Jianshu in QQ When applying for the Internet platform, it must have reserved the records to jump back URL.QQ When the Internet platform receives the authorization request of the profile, it will definitely verify the callback Url Of .

3.2. Step 2 : 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 first post 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 Make a jump , And return the authorization code code And the state.
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 book Url by :

http://www.jianshu.com/users/auth/qq_connect/callback?code=093B9307E38DC5A2C3AD147B150F2AB3
&state=bb38108d1aaf567c72da0f1167e87142d0e20cb2bb24ec5a
And previous authorization requests URL Compare , It can be found that redirect_uri,state Exactly the same .
and code=093B9307E38DC5A2C3AD147B150F2AB3 Is the returned authorization code .

3.3. Step 3 : 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 book QQ 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 use QQ I've logged in to Jianshu .
* token (Access Token): Equivalent to temporary ID card .
How to apply for a token ?
Jane needs to send a get Request to authentication server (QQ Internet 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", Required ;
* client_id: From QQ Clients applied by Internet platform ID, Used to flag the source of the request , Required ;
* client_secret: This is from QQ Client authentication key applied by Internet platform , Confidential information is very important , Required ;
* 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 application AccessToken Request for :
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 of , In seconds .
* refresh_token: In the authorization auto renewal step , Get new Access_Token Parameters to be provided when .
same , We can simulate a return token:

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 users token write to cookie in , Maintain user login status . Let's turn on the controller and verify .



It can be seen from the figure that the user token Save in the remember_user_token Of cookie in .
No need to fight cookie It's a bad idea , It must be encrypted .
You can try the manual remember_user_token This one cookie delete , Ensure that you need to log in the profile again after refreshing the interface .

3.4. Step 4 : Request resources from resource server

Yes token, Send a to the resource interface provided by the resource server get 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 use token request QQ User basic information resources URL:
https://graph.qq.com/user/get_user_info?client_id=100410602 &qq=2098769873
&access_token=548ADF2D5E1C5E88H4JH15FKUN51F

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

3.5. Step 5 : Token extension ( Refresh )

You must have returned to step four refresh_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's also possible
Delay expired tokens .

for instance ,QQ Internet platform for security , Returned access_token There's a time limit , What if the user doesn't want to authorize one day , I can't give you one access_token
You can use it in a few years . The validity of the token returned by our above simulation is 10 hour .10 Hours later , User opens browser to browse brief books , User's in browser token Corresponding cookie Expired . Jianshu finds that the browser is not carried token Information come here , I understand token It's not working , Need to re apply for authorization from the certification platform . If the user clicks again QQ Login authorization , This is obviously a bad user experience . What's going on ?
refresh_token
That's where it comes in , You can directly skip the previous steps of applying for authorization code , When found token It's not working , Jane's book from browser cookie In sessionid Find the
refresh_token, Then use refresh_token conduct token Renewal ( Refresh ).

That's for refresh_token conduct token What do I need to do to renew it ?
You also need to send a get request .
What parameters are required ?

* grant_type: Indicates authorization type , The value here is fixed to "refresh_token", Required ;
* client_id: From QQ Clients applied by Internet platform ID, Used to flag the source of the request , Required ;
* client_secret: This is from QQ Client authentication key applied by Internet platform , Confidential information is very important , Required ;
* refresh_token: That is, the returned refresh_token.
Based on the above information , We can simulate a token refresh URL:
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 one refresh_token, Can't I use it refresh_token Unlimited extension of time ?
Naive as me ,refresh_token It also has expiration time . The expiration time is determined by the authentication server .
generally speaking refresh_token Expiration time of is greater than access_token Expiration time of . That's all ,access_token When expired , Can be used
refresh_token Extend token ( Refresh ).

A simple example :
Suppose that Jianshu QQ Obtained by default from the Internet platform access_token Is valid for 1 day ,refresh_token Valid for one week .

Users use today QQ After login authorization , After two days, I'll go shopping in Jianshu , Jianshu discovery token invalid , For immediate use refresh_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 fail , You can only guide the user to the authorization page to reauthorize , That is, back to OAuth2.0 The first step .

4.0 summary

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

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

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