preface
First, be clear about three concepts:
certification
- In plain English
Verify the identity of the current user
Prove that you are yourself - Authentication on the Internet:
- User name and password for login
- Email sends the login link
- Mobile phone number Receiving verification code
- As long as you receive the email/verification code, you are the account owner by default
authorization
- The user
Grant third-party applications
Permission to access certain resources of the user- When you install an APP on your phone, the APP asks you if you can grant permissions (access to albums, geolocation, etc.)
- When you access the wechat mini program, when you log in, the mini program will ask whether you are allowed to grant permissions (to obtain personal information such as nickname, avatar, region and gender).
- The authorization modes are cookie, session, Token, and OAuth
credentials
- To implement authentication and authorization, a medium (certificate) is required
Mark the identity of the visitor
- It’s like everyone’s ID card
The Nuggets, for example, have two modes:'Tourist mode'and'Login mode'. In visitor mode, you can normally browse the articles on the website, and when you want to like/favorites/share an article, you can'Need to log in or register an account'. When the user logs in successfully, the server issues a token to the browser the user is using (`token`), this token is used to'Identify yourself'.Every time ` `When the browser sends the request'will bring'This token allows you to use functions that are not available in tourist modeCopy the code
User Login scheme
- Cookie + Session indicates the login state
- Token indicates the login state
- OAuth Third-party login
Cookie + Session indicates the login state
Preface introduces
Let’s take shopping mall and shopping cart as an example to introduce:
For the mall home page, all users browse the goods are the same, users can access without logging in. At that time, if the user chooses to add the goods to the shopping cart or add them to the favorites, we need to have the credentials that can identify the user’s identity, which can adopt the mechanism of cookie + session to log in
What is a session
When a user logs in to a website for the first time, the browser sends a request to the server, and the server will temporarily create a memory space for this request, which is the session object. The session object is to record some state or behavior records of the user
The question is, how does the server know which user initiated the request from the browser? Cookie comes in
What is a cookie
In simple terms, a cookie is a small piece of data that the server sends to the user’s browser through the set-cookie field in the response header and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server. It is used to keep the user logged in, and in conjunction with the session can be used to communicate who the user is
See the Browser series – Local Storage for more information on cookies
The difference between cookies and sessions
- Storage location: Cookie in browser, session in server (generally in memory)
Shopping cart data is generally placed in'database'The purpose of the session is not to store shopping cart data, but to let the server know which user it is` tool `Just. Why does the session not store the shopping cart data, because the user logs out after the cookie expires, and after logging in again, the session is replaced, which means the shopping cart data will be emptiedCopy the code
- Security factor: Low cookie security factor, session
High safety factor
- Valid time: cookie looks set
The period of validity
If it is not set, then the window closes and the session disappears. In memory, the window closes and the session disappearsCan be a long time
- Performance: Cookies do not cause heavy pressure on the server, but session does when the number of users is too large
Server under high pressure
- Store content: The data stored in cookies is generally the user
nickname
,account
And so on some non-private data, whereas sessions are generally storedpassword
And someID
Private data like that - Type of data stored: Cookie Yes
String type
Sessions can be of any type, mainly key-value pairsHash table type
orThe Object type
The connection between cookies and sessions
Both are session methods to track the identity of the browser user, and they can be used as login mode together
Let’s take a look at how cookies and sessions work together:
The implementation process
- User’s First Login
- After a user logs in for the first time, the server allocates a memory space for the user
session
And generate the correspondingsession id
.session
It’s like a gunThe lock.session id
This is the lock that unlocked itThe key - The server then sends this key through the response header (putting the session ID in the response header)
Set-Cookie
Field) - When the browser receives the response, it stores the session ID
cookie
The cookie’s expiration date is the same as the key’s expiration date, which meansOnce the cookie expires, the login state is invalid
, indicating that the user logs out (passive logout)
- Access after login
- The user is currently logged in and then visits the site and makes requests (such as adding items to a shopping cart)
- At this time, the browser automatically carries the cookie belonging to the user under the domain name in this request according to the requested domain name, (which contains
session id
) - If the server side learns that the lock is opened (in memory)
session
And receivedsession id
Yes), runs to the database to retrieve the user’s data stored in the database (shopping cart) and returns it. - But if it doesn’t, for example, the cookie expires, the server returns a status code
401
, the browser will ask the user to re-enter the account and password to log in
Token indicates the login state
Why do YOU choose to use token instead of session+cookie for login?
- High server stress: Since sessions are usually stored in memory (due to fast access times), the memory space will be overwhelmed when the number of users increases
- Cookies are vulnerable to CSRF attacks (GET and POST requests can be forged in the same way, and just relying on the browser to read the domain name automatically carry cookies to complete authentication is too insecure, relying on a hacker can not forge: Tokens are safer in the POST form.
- Cookie expiration means that the user is logged out and has a bad experience
- If the browser/web page disables cookies, use token for login
classification
- Acesss token: used to access resource interfaces
Proof of resources
Basic components of Access Token:1.Uid (unique user identity)2.Time (timestamp of the current time)3.Sign (a hashed hexadecimal string with the first bits of a token)Copy the code
- Refresh Token: Dedicated to
Refresh the access token
The token
If there is no refresh Token, the Access token can also be refreshed, but each refresh requires the user'Reenter'Login username and password, can be very troublesomeCopy the code
How to use access Token for login
- When a user logs in for the first time, the server verifies the user name and password
encryption
theaccess token
On theResponse headers
Send the access token to the browser (preferably over HTTPS), the browser receives the token and places it incookie
orlocalstorage
Inside [note this serverDo not save
access tokenBut save
The refresh token. - The user is currently logged in, then visits the site and makes a request (such as adding goods to the shopping cart), carrying the token placed in the
Request header
Inside send to the server - Server according to
JWT algorithm
Decrypt and verify token, verify successful,Stay logged in
(In this case, you can refresh the timeout period of the Access Token to prolong the login time), if the authentication fails, the server uses refresh token to refresh the token to obtain the latest Access token and send it to the browser
In this way, the time spent parsing tokens is used to exchange the storage space of the session and reduce the memory space pressure of the server
See the JSON Web Token Tutorial for details on the JWT algorithm
How can I use refresh Token to refresh access Token
If the access Token authentication fails, the browser needs to update the Access token by using refresh Token
- The validity period of the Access token is short (for example, one week), and the validity period of the refresh token is long (for example, one month). If the ACesss token expires but the refresh token does not expire, The refresh token can be used to obtain a new token
- If the Refresh Token also fails, the server returns a status code in the response header
401
, the browser receives the status code and asks the userLog back in
- The refresh token and expiration time are stored in the server’s database and are validated only when a new ACesss token needs to be applied for
Has been requested
And it doesn’t have to be persistent like a sessionmemory
In order to handle a large number of requests (this is the use of token for login state can lighten the serverMemory pressure
The embodiment of the)
How do YOU remember your password?
Because the security factor of the account is not high, the account can be stored in cookie or localstorage as a plaintext string. If the user selects remember the account, The next time you log in front-end JS code will through the document. The cookie or the window. The localstorage. After the getItem access to the account number is added to the < input >, do remember the function of account.
Because passwords require high security, we generally do not store passwords locally (whether in plain text or ciphertext), or to be exact, we do not do the function of remembering passwords, we use the token mechanism instead. The token can be stored locally, and the client only needs to send the token to the server for verification during the next login.
- If the user checks “remember password” or says “Remember user,” it’s essentially
Make the refresh Token valid for a long time
. - If the user doesn’t check “Remember password,” it’s essentially
The refresh token validity period is the same as the Access token
Assume that the validity period of the Access token is two hours. If the user goes online after two hours, the login status of the user is invalid because there is no refresh token to refresh the Access token. In this case, the user needs to re-enter the password for login.
How to retrieve the password function?
User if forget the password, retrieve password, right now we are the most important thing is to confirm that the user identity, if the user has a binding mobile phone number can use a mobile phone number before sending mobile phone verification code verification, if the user have binding mailbox, before we can get E-mail link sent via email to the user, the user received an email after open the link to complete the authentication. After authentication, the server sends the password to the client. (Captcha are only valid for a short period of time)
Note that the server cannot save and send passwords in plain text or ciphertext. The best solution is to maintain a hash table to store passwords, and then the server will pass the hash to the client for future use.
How does the password reset function work?
Or is it the same as retrieving the password to first carry out forcible interaction authentication with the user, and then give a link to reset the password (because the link is clear text transmission, so it must be valid for a short time)
OAuth Third-party login
OAuth mechanism implementation process
Here, take the wechat login and access process of website application as an example :(The official documentation)
- I. Website operators apply for accounts
- First, a.com operators need to register an account on wechat’s open platform and apply to wechat to use its login function.
- After the application is successful, the applicant gets the application
appid
,appsecret
.
- User login and authorization
- Users choose to log in using wechat from a.com.
- At this time, it will jump to wechat OAuth authorized login, and bring the callback address of a.com.
(A page pops up: HTTPS:/ /open.weixin.qq.com/connect/qrconnect?appid=`APPID`&redirect_uri=`www.a.com`
&response_type=`code`&scope=`snsapi_login`&state= state #wechat_redirect, this page shows a QR code)Copy the code
- The user opens the wechat APP
scan the code
After that, you need to select specific onesauthorization
Range, such as the profile picture and nickname of an authorized user.
- Iii. Wechat generates temporary bills
- After authorization, wechat will
redirect
toredirect_uri
theThe url
Go up and put it oncode
andstate
parameter
- Iv. Websites request access tokens from wechat
- After obtaining the code, a.com will carry the code, AppID and AppSecret and call the interface provided by wechat official to the wechat server
Apply for token
After the authentication succeeds, wechat sends the Access Token and the corresponding refresh token to refresh the Access Token.
The access_token validity period is currently'2 hours'Refresh_token is currently valid for` ` 30 days
Copy the code
- After obtaining the Access token, a.com can carry the Access token to call the wechat interface, and obtain the user’s wechat account like, user nickname and other information.
- The user is prompted to log in successfully and the login status (including the user profile picture nickname and the Access token and Refresh token) is written
cookie
或localstorage
As a credential for subsequent access.
- 5. Next login
- After a user logs out or the login status becomes invalid, the browser sends a request to the server and carries the information saved last time
access token
, the server verifies whether the token is valid after receiving it, ifaccess token
Not expired, then a.com can directly take it to call the wechat interface to obtain user profile picture, nickname; - if
access token
If the refresh token and appID are expired, the server invokes the wechat interface to obtain the latest Access token and replace the old access token. - If the Refresh Token also expires, the server receives an error code
{"errcode":40030,"errmsg":"invalid refresh_token"}
At this point, the user needs to go back to step 2 and re-authorize the login.
Access to other platforms can go to the due official documents, the process is basically similar.
Refer to the article
- Cookie, Session, Token, JWT
- Common front-end login implementation scheme + single sign-on (SSO) solution
- Read this Session, Cookie, Token, and bicker with the interviewer will be no problem