This paper participated inNuggets surrounding gifts 🎁 campaignOh, and leave a comment in the comments section for a chance to get free nuggets gifts, see the bottom of the article for more details
Login function, I believe you do in the project must have
So how to achieve login, what is the specific process? Recently a friend interview encountered this question said not to come up, and then to ask me, emmmm…..
We all know that HTTP is a connectionless stateless protocol, that is, each request is independent, and the server cannot distinguish whether each request is from the same user, so it cannot determine the login status
To solve this problem, we need some processing scheme to record the login status
Therefore, this paper will be developed from three aspects
- Chapter 1 mainly describes how to log in to the interface in different login modes
- The second chapter mainly introduces the following methods and differences of interface login status verification
- The third chapter mainly introduces single sign-on, because this is a little special, so singled out
Let’s find out
Initial Login Process
First, take a look at the processes to be processed by the front and back ends in different login modes, and refer to the next chapter for the successful return process of the login interface
Account and Password Login
This will not demonstrate the code, collect the user name and password input, send to the backend and the database for comparison and verification, whether the user exists, password is correct, all OK to return the login success and user information
Some will add a graphical verification code or something like that, which is called the call interface, and then the backend will randomly generate the graphical verification code and store it in session or token (depending on the login authentication method used by your project, in the next section of this article) and send it to the front end for display
The front endpoint collects the verification code entered by the user during login, compares it with the back end, and returns the login success and user information
Mobile phone verification code login, email login
This is also easy, I won’t show you the code, such as mobile phone verification code login
The front end clicks to send the verification code, and the mobile phone number is transmitted to the back end, which generates a random number, and then sends the number and complete SMS content (including random number) to the third party SMS platform (such as Ali, yunchip…..) A lot of)
Some people store their phone number and random number in the database in the callback of successful SMS sending by the third party, and some people store the number and random number in the database after generating good random number, and then update the callback returned by the third party
For example, the content of the message sent does not meet the specification, the SMS platform is out of money, and the SMS platform is abnormal. There is also a log there
After receiving the SMS message, the user logs in. The front-end collects the mobile phone number and verification code and sends them to the back-end and database for comparison. If the verification is successful, the login and user information are returned
The logic of an email verification code is basically the same as that of a mobile verification code. If a third-party email platform is used, the receiver of the verification code changes from the mobile phone number to the email number
Quick login with a third-party account
First of all, third-party account login needs to apply for authorization
Such as QQ and wechat
When the front end enters the login page, it calls the interface to obtain the link address to jump to the third party login page (it is better not to write dead on the front end). This address is splicted with the encrypted signature of the back end and the redirect_URI address after successful login (the details can be determined by what the official documents of the third party login need to be transmitted).
Example of QQ login address
https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=101958498&redirect_uri=http%3A%2F %2Fniuj.uuuqwr.cn%2Findex.html%23%2Foauth_login%2Fqq&state=24c123db52d1136c7560638325fbdab4&scope=get_user_info,list_alb um,upload_picCopy the code
Note that this callback address (redirect_URI) must be a separate page in your project, which is used to change the login status by receiving the parameters from the callback link, not your project’s login page or personal center
Then, for example, if you click QQ to log in, you will directly jump to the third party login link returned by the back end, which is the following
Then, when we log in to this page, the third party will generate the signature in the same way and obtain the signature in the URL for comparison. If the comparison is successful, it means that we can log in, and then splicken the verified parameter code to the redirect_URI address carried in the URL, and then jump to it
The front end in this jump back address page, after getting and then passed to the back end, and then the back end to tune the third party interface, get the login user openId, unionId, and database comparison, no user registration, and save openId, unionId
Then return the login status to the front end, and some need to let you bind the mobile phone number to give you the login success, here depends on your business needs, the front end according to the return of different states for login success or binding machine number and other operations
For example, after wechat login, a QR code is generated on the current page according to the redirect_URI and AppId information returned from the back end, or a new TAB page is opened to jump to a separate scan page
For example, to generate the TWO-DIMENSIONAL code in the current page, I use vue-wxlogin, first install
npm install vue-wxlogin --save
Copy the code
Then use the
<template>
<wxlogin
:appid="appid"
:scope="scope"
:redirect_uri="redirect_uri"
self_redirect="false"
theme="white"
></wxlogin>
</template>
<script>
import wxlogin from "vue-wxlogin";
export default {
data(){
return {
appid: "wx989xxxxxxxxx".scope: "snsapi_login".redirect_uri: encodeURIComponent(
"http://xxxxxx/index.html#/oauth_login/wx")}}}</script>
Copy the code
After the QR code is generated, the third party will start polling, as follows
Then sweep the code after the login process and QQ fast login process is basically exactly the same
App scan code login
First you need to generate the QR code, I’m using vuE-QR here, install it first
npm install vue-qr --save
Copy the code
Then use the
<template>
<vue-qr
:text="qrCode.url"
:margin="5"
colorDark="# 222"
colorLight="#fff"
:logoSrc="qrCode.icon"
:logoScale="0.2"
:size="180"
></vue-qr>
</template>
<script>
import VueQr from "vue-qr";
export default {
data(){
return {
qrCode: {url:' '.icon:' '.// This is the image in the middle of the qr code}}},mounted(){
this.getQrCodeInfo() // Call the interface to obtain the information required to generate the TWO-DIMENSIONAL code}}</script>
Copy the code
Here’s how it works
-
Enter the page first to obtain the information required to generate the TWO-DIMENSIONAL code, adjust the interface
-
The backend then generates such things as uuid, sets the expiration time and stores it in the cache, and returns information such as UUID to the front end
-
After the front end gets the information, it uses the information as the URL in the above code to generate the TWO-DIMENSIONAL code, and then calls another interface to pass the UUID, and opens the round, or long connection, or directly listens with WebSocket without tuning the interface. Which one to use depends on your business needs or consult with the backend
-
Then the mobile phone side must be in the login state, otherwise it can not scan code login, and then the App scan code, will get the UUID in the TWO-DIMENSIONAL code
-
Then after the phone endpoint logs in, it sends the UUID and the account information of the user that logged in to the phone to the back end
-
The back end gets the login account information and sends it to the front end through WebSocket. Then the login is successful. Or modify the value in the cache, for example, when storing the UUID, the UUID is used as the key, but there is no value, and then the polling interface is to obtain the value of the UUID, before the login is empty, after the App login, the backend will get the user information as a value to the corresponding UUID. The data queried by the front end is not empty, indicating a successful login, and then the back end clears the cache
Fingerprint login, face login, the local number without encryption one key login
This is all for mobile, iOS and Android, and both require an SDK
I haven’t done this since I’m mostly on the Web side. Personally, I understand that the general process should be a page for users to confirm the opening of these functions, or a popup window for authorization to obtain information, so that users can authorize
For example, if the local number is used for one-click login without encryption, the user can access the SDK and communicate with the carrier to obtain the user’s mobile phone number
Then the user clicks one-click login authorization, compares the gateway numbers, and returns the comparison results to achieve one-click login
Verify the subsequent login process
There are two common login authentication methods
- Cookie + Session
- Token
Regardless of the login method, the authentication principle is currently dependent on the above two
Continuing the previous section, assuming that the login request is authenticated at the back end, the flow is as follows
Cookie + Session
Here’s how it works
-
After the first successful login, the backend creates a Session object and stores it in the cache or database
-
Then in the response header of the response login interface, Set the set-cookie field, and write in the SessionId and other information, and Set the expiration time, these information is Cookie, and then the browser will save these Cookie information
-
If the current domain name stores Cookie information, the browser automatically adds a Cookie field to the request header and carries the saved Cookie information
-
Then, after receiving the request, the backend will extract the Cookie information in the request header and compare it with the corresponding Session information existing on the server. If they are consistent, the login authentication is successful and there is no need to log in again
For example, the Nuggets login through this way, this is the Nuggets login interface return, you can see the SessionId and a bunch of other information
However, nuggets turn off the request when the browser automatically carry cookies in the request header, but the Cookie information stored in the cache, and then the following whole pass, and then the login status is also saved, which is not clear about the specific logic, should avoid the risk of CSRF attack
Disadvantages of this approach
This is mainly CSRF attacks: if every request carries a Cookie, it can be intercepted and someone can use our Cookie information to skip the login and go directly to the login and do something bad
If the Session is stored in the server memory but not in the database, the following problems will occur
-
Multiple servers cannot be shared: for example, when we log in, different resources of our website may have different servers. When we request another server, there will be no Session information in it, and it will be considered that we have not logged in. As a result, front-end code and back-end code can only be placed on the same server
-
High pressure on the server: The Session information is stored in the memory after users log in. If there are a large number of users, the pressure on the server will increase
Token
The process is similar to the Session above
-
After the first login authentication is successful, the back-end uses JWT to encrypt user information and signature to generate a string of strings, which are stored in the database and returned to the front end
-
Front-end storage again, there are cookies, SessionStorage, LocalStorage can be
-
The browser will not carry the Token by default when we request again. We need to add the request header in the request interceptor and bring the Token information
-
Then the backend will get the Token information to check whether there is any data in the database. If there is any data returned by the front-end request, such as query database operation, because the expiration time is set, Redis will automatically delete the Token in the database when the time is up, and the query will not be there. Of course, some people are on a scheduled task to delete
Some people do not save the Token in the database, but when generating the Token, encrypt the user information and expiration time and send them to the front end. When making a request, the back end decrypts the decrypted user information after getting the Token, and then queries the decrypted user information. If the query is found and has not expired, the query returns the data requested by the front end
For example, if multiple logins are not allowed, one login will force the other to log off. This means that only one Token is allowed for an account, and then another login will generate a new Token and save it in the database. The original Token will be replaced, and the login place with the previous Token will be logged off
On the other hand, if you need to allow multiple logins, that is to say, a user can have multiple tokens
The characteristics of this approach
A more secure
: Because cookies are not sent, CSRF attacks can be avoided. You don’t need to manipulate sessions anymoreMultiple servers facilitate sharing
: Resources such as the front-end and back-end code files are stored on different servers, and the correct login status can be obtained at request
Single sign-on (SSO)
Simply put, an account registered in one application can be logged in to multiple applications at the same time
For example, Taobao + Tmall + Alipay + Alibaba… , these several random login which one, and then open a few other websites will automatically enter the login state
Its login methods are described in chapter 1 of this article, and subsequent authentication methods are described in Chapter 2 of this article
One of the key points is how do you connect multiple applications?
And if you’re using cookies, there’s a limitation that cookies can’t cross domains, so you have to solve this problem
And in the same domain of different domains under the single sign-on is also different, online read a lot of information said unclear, I also did not do this kind of multi-application single sign-on, so here only summarized the general process, their own record, do it again after perfect it
The same domain
For example, Baidu.com, Pan.baidu.com, Tieba.baidu.com, map.baidu.com…
Single sign-on is implemented in this case
The first step is to set the Cookie to the top-level domain so that all of its subdomains can access it
Then through Redis, Tomcat, etc., you can set the Session to be shared among these domain names
This links several applications together, and the rest of the process is pretty much the same as above
Different domains
Such as Taobao.com, Tmall.com, Alipay.com, Alibaba (1688.com)…
We can also share cookies with top-level domains, but we can’t share cookies with completely different domains. What can we do?
Therefore, to solve this problem, we need a separate authentication authority (CAS), namely SSO login system, which can manage or share the status information uniformly, or can be understood as a relay station
For example, we now have two sites: a.com and b.com that need to share login status
The login
First of all, when you enter the page to be logged in to a.com/user without login, you will be redirected to the authentication center and take your own address as a parameter, for example
sso.com?redirect_uri=a.com/user
Copy the code
The authentication center then finds that there is no Ticket in the login request, that is, the user has not logged in, and goes to the login page. All logins are performed in the authentication center
After a user enters information and submits a login request, the authentication center verifies the user information. After the verification succeeds, the authentication center generates an authorization code Ticket, writes the login status of the authentication center into a Cookie, and then rewrites the information to the previous page with the Ticket
a.com/user?ticket=xxxxxxx
Copy the code
Then a.com/user gets Ticket and confirms to the authentication center whether the authorization code is valid. After successful verification, the server writes the login information into cookies and returns them to the front end for storage. At this time, the a.com has two cookies, which are the login status of itself and the authentication center respectively. The login is successful
Why do I need to confirm to the certification center after I get a Ticket? Because if you do not verify again, for example, we directly enter the address of the callback in the address bar, and splice false information parameters, not directly considered login, this of course not, so you need to verify again
Then b.com also accesses the page to be logged in to. When it re-writes to the authentication center, it finds the Cookie that it has logged in to before, so it sends Ticket to b.com directly
Then b.com gets Ticket and verifies it with the authentication center. If the authentication is successful, the login information is written into the Cookie and returned to the front end for storage. At this time, the login state is displayed without entering the login page
The cancellation
When one application logs out, all other applications that share login automatically log out
For example, when a.com logs out, it first clears its login status Cookie, and then carries Ticket to request the authentication center’s exit API
After verifying that Ticket is valid, the authentication center iterates through all applications under the authorization code and invokes the corresponding exit API
That completes the exit of all applications
Advantages and disadvantages of single sign-on
advantages
- Good user experience, no need to remember multiple accounts and passwords
- Improve development efficiency
- Convenient management
journey
title My working day
section Go to work
Make tea: 5: Me
Go upstairs: 3: Me
Do work: 1: Me, Cat
section Go home
Go downstairs: 5: Me
Sit down: 5: Me
disadvantages
- Refactoring is not conducive because there are many systems involved, and refactoring requires compatibility with all of them, which is very troublesome
- There are security risks. After all, you only need to log in once and all authorized applications can be directly accessed, which may lead to some information leakage
Past wonderful
- Vue3 7 and Vue2 12 components communication, worth collecting
- What are the latest updates to Vue3.2
- JavaScript advanced knowledge
- 22 high frequency handwritten JavaScript code to learn
- Front-end anomaly monitoring and DISASTER recovery
conclusion
This paper participated inNuggets surrounding gifts 🎁 campaignAll you have to do is leave a comment in the comments section of this article, and by 24:00, September 12, the two workers with the most likes in the comment section will receive the nuggets’ new badge, XDM, for free
Praise and support, hand left lingering fragrance, and have honor yan
Thank you for being here!