An overview of
Recently, I was reconstructing the login system of a project of the company. I took this opportunity to summarize the front-end login system scheme
At present, several common login schemes:
Cookie + Session
The loginToken
The loginSSO
Single sign-on (sso)OAuth
Third-party login
So let’s start with Cookie + Session
1. Cookie + Session
HTTP
A stateless protocol in which each time a client sends a request, it establishes a connection to the server and then disconnects the connection after the request is completed. This method saves the connection resources used during transmission, but there is also a problem:
Each request is independent, and the server cannot determine whether this request and the previous request are from the same user, and thus cannot determine the user’s login status.
In order to solve the
HTTP
The problem of statelessness, Lou Montulli introduced in 1994
Cookie
.
Cookie
A special message sent by the server to the client in the form of text, which the client carries with it every time it sends a request to the server.
In B/S systems, the login function is usually based on
Cookie
To do that. When the user logged in successfully, the login status will generally be recorded
Session
In the. To implement the server to verify the client’s login information, it is necessary to save some information in the client (
SessionId
) and require the client to carry them on each subsequent request. In such a scenario, use
Cookie
Is undoubtedly the most convenient, so we generally will
Session
的
Id
Save to
Cookie
When the server receives the request, it passes the validation
Cookie
To determine whether the user is logged in.
At first login:
- The user to access
some.com/pageX
And enter your password to log in. - After the server verifies that the password is correct, it will be created
SessionId
“And save it. - The server side responds to this HTTP request and passes
Set-Cookie
Header information that willSessionId
writeCookie
In the. - Server side
SessionId
It may be stored in many places, such as memory, files, databases, etc.
After the first login is completed, subsequent access can be used directlyCookie
Authenticated:
- The user to access
a.com/pageB
Page, will automatically bring the first login writtenCookie
. - Server-side alignment
Cookie
In theSessionId
And saved on the server sideSessionId
Consistent. - If they are consistent, the authentication is successful and the page is accessed. If this does not work, the user is required to log in again.
Cookie+Session:
- Because the server side needs to connect with a large number of clients, it also needs to store a large number of
SessionId
, which can cause the server to become overstressed. - If the server side is a cluster, in order to synchronize the login state, you need to
SessionId
Synchronize to each machine, virtually increase the maintenance cost of the server. - Due to the
SessionId
Stored in aCookie
So it can’t be avoidedCSRF
Attack.
2. Token login
A Token is a string generated by the server as a Token requested by the client. After the first login, the server will generate a Token and return it to the client, and the client will only need to carry the Token to complete the authentication for subsequent visits.
At first login:
- The user to access
some.com/pageX
Enter your account password and click Login. - Server side to verify the account password is correct, create
Token
. - The server side will
Token
Returns to the client byThe client is free to save.
During subsequent visits:
- The user to access
some.com/pageY
Bring the one you got the first time you logged inToken
. - The server side validates this
Token
, valid authentication is successful, invalid kicked back to the new login.
Token generation mode
The most common way to generate tokens is to use JWT (JSON Web Token), which is a neat, self-contained method for securely passing information between two parties in the form of JSON objects.
After using the Token, the server does not store the Token, so how can we tell if the Token sent by the client is valid and legal?
The answer lies in the Token string. The Token is not a random string, but a string that is stitched together by a variety of algorithms.
The JWT algorithm has three main parts: Header (header), PlayLoad (message body), and Signature (signature).
header
Section specifies theJWT
The signature algorithm used;playload
In part to show thatJWT
Intentions;signature
Part isJWT
In order to makeJWT
It can’t be tampered with.
Token advantage
- No storage is required on the server side
Token
, so there will be no pressure on the server side, even if the server cluster, there is no need to increase the maintenance cost.Token
I can store it anywhere on the front end, I don’t have to store it inCookie
In, improve the security of the page.
Token is insufficient
Token
After it is issued, it remains in effect for as long as it is in effect, but if the server wants to recall itToken
The permissions are not easy.
SSO single sign-on
Single sign-on refers to the multiple application systems under the same account platform, users only need to log in once, can access all the mutually trusted application systems. Essentially, sharing login status across multiple applications. For example, Baidu Tieba and Baidu Map are two different application systems of Baidu Inc. If a user has logged in in Baidu Tieba and does not need to log in again when he visits Baidu Map, then a single sign-on has been achieved between Baidu Tieba and Baidu Map.
Process:
- User access to the site
a.com
Under thepageA
Page. - Because you are not logged in, you are redirected to the Authentication Authority with the callback address
www.sso.com?return_uri=a.com/pageA
In order to login directly into the corresponding page. - The user enters the account password at the authentication center and submits the login.
- The Authentication Authority verifies that the account password is valid and then redirects
a.com?ticket=123
With an authorization codeticket
And will certify the centersso.com
Login state write toCookie
. - in
a.com
On the server, hold itticket
Check with Certification Authority for the authorization codeticket
True and effective. - After successful verification, the server writes the login information
Cookie
(At this point, the client has twoCookie
Are therea.com
和sso.com
Login state of.
After the Authentication Authority login is complete, continue accessa.com
Other pages under:
At this point, because
a.com
There is a logged in
Cookie
Message, so the server side directly authenticated successfully.
If the Authentication Authority login has completed, accessb.com
Page below:
At this time, because the authentication authority has previously logged in
Cookie
, so do not need to enter the account password again, directly back to step 4, send
ticket
给
b.com
Can.
How the SSO mechanism is implemented
There are three main ways to implement single sign-on:
- The parent domain Cookie
- Certification center
- LocalStorage cross-domain
In general, the user’s login status is recorded in the Session. In order to achieve shared login status, it is necessary to share the Session first. However, since different applications have different domain names, even though the Session is shared, However, since SessionID is usually stored in the browser Cookie, there is scope limitation and it cannot be passed across the domain name. That is to say, when the user logs in from a.com, the Session ID will only be carried automatically in the request header when the browser visits a.com. When the browser accesses b.com, the Session ID is not carried. The key to implementing single sign-on is how to share the Session ID (or Token) across multiple domains.
1. The parent domain Cookie
The scope of the Cookie is determined by the domain attribute and the path attribute. The valid value of the domain property is the domain name /IP address of the current domain or its parent domain, and in Tomcat, the domain property defaults to the domain name /IP address of the current domain. A valid value for the path attribute is a path beginning with a “/”, and in Tomcat, the path attribute defaults to the context path of the current Web application.
If the domain property of a Cookie is set to the parent domain of the current domain, it is considered a parent domain Cookie. Cookie has a feature that the Cookie in the parent domain is shared by the quilt domain, that is to say, the child domain will automatically inherit the Cookie in the parent domain.
Using this feature of cookies, you can simply store the Session ID (or Token) in the parent domain. We only need to set the domain property of the Cookie to the parent domain (master domain) and the path property of the Cookie to the root path, so that all sub-domain applications can access the Cookie. However, this requires the domain name of the application system to be under a common master domain, such as tieba.baidu.com and map.baidu.com, which are both under the master domain name baidu.com, so that they can achieve single sign-on in this way.
Summary: This implementation is relatively simple, but does not support cross-primary domain names.
2. Certification center
We can deploy a authentication authority, which is a separate Web service dedicated to handling login requests.
The user logs in at the authentication center uniformly. After successful login, the authentication center records the user’s login status and writes the Token into the Cookie. (Note that this Cookie belongs to the Certification Authority and is not accessible to the application system.)
The application system checks whether there is a Token in the current request. If there is no Token, it means that the user has not logged in in the current system, and then the page will be redirected to the authentication center to log in. Because this operation automatically passes the authentication authority’s Cookie, the authentication authority can know whether the user has logged in or not based on the Cookie. If the Certification Center finds that the user has not logged in, it will return to the login page and wait for the user to log in. If it finds that the user has logged in, it will not let the user log in again. Instead, it will jump back to the target URL, generate a Token before the jump, spliced it behind the target URL, and send it back to the target application system.
After the application system gets the Token, it also needs to confirm the validity of the Token with the authentication authority to prevent the user from counterfeiting. After confirmation, the application system records the user’s login status, writes the Token into a Cookie, and then allows the access. When the user visits the current application again, it will automatically carry the Token. The application verifies the Token and finds that the user has logged in, so there will be no problem with the authentication authority.
Conclusion: This implementation method is relatively complex, supports cross-domain, good scalability, is a single sign-on standard practice.
3. The LocalStorage across domains
The key to single sign-on is how to share the Session ID (or Token) across multiple domains. But the Cookie is not supported across the master domain, and the browser to the Cookie across the domain restrictions are more and more strict.
In the case of the separation of front and back ends, it is completely possible not to use cookies. We can choose to save the Session ID (or Token) to the localStorage of the browser, so that the front end will take the initiative to transfer the data of localStorage to the server when sending a request to the back end each time. These are controlled by the front end, and all the back end needs to do is pass the Session ID (or Token) in the response body to the front end after the user logs in successfully.
In such a scenario, single sign-on can be implemented at the front end. After the front end gets the Session ID (or Token), in addition to writing it to its own localStorage, it can also write it to the localStorage of several other fields by special means.
Summary: This implementation is completely front-end controlled, requires little back-end involvement, and also supports cross-domain.
SSO single sign-on logout
At present we have completed the single sign-on, under the same set of certification authority management, multiple products can share the sign-on status. Now we need to consider logging out, i.e. if you log out of one product, how can you log out all the other products as well?
The principle is actually not difficult. When each product verifies its ticket(token) to the certification center, it can actually send its own logout API to the certification center.
When a product c.com logs out:
- empty
c.com
Login state inCookie
. - Request Certification Authority
sso.com
The exitapi
. - Certification center traversal issued
ticket(token)
All products and call the corresponding exitapi
, complete the exit.
IV. OAuth third party login
The third-party login mode of OAuth usually uses the following three ways:
- WeChat login.
- Login on Weibo.
- Qq login. And so on…
Here, the access process of WeChat open platform is taken as an example:
- First of all,
a.com
The operators of WeChat need to register an account on the WeChat open platform and apply to WeChat for using the WeChat login function. - After the application is successful, the applicant obtains the application
appid
,appsecret
. - The user in
a.com
Select to log in using WeChat on. - This will jump to WeChat OAuth authorized login, and bring
a.com
The callback address of. - User input WeChat account and password, login successfully, need to choose the specific scope of authorization, such as: authorized user’s avatar, nickname, etc.
- After authorization, WeChat will pull according to
a.com?code=123
“And took a temporary note with himcode
. - To obtain
code
After that,a.com
Will take acode
、appid
,appsecret
, apply to WeChat servertoken
, WeChat will issue one after the verification is successfultoken
. - There are the
token
After that,a.com
You can rely ontoken
Get the corresponding micro credit account like, user nickname and other information. a.com
Inform the user of successful login, and write the login statusCookie
To be used as a credential for subsequent access.
The access of other platforms can go to the due official document view, the process is basically similar.
conclusion
Cookie + Session
It has a long history, lends itself to simple back-end architectures, and requires developers to take care of security issues themselves.Token
The solution has little pressure on the backend and is suitable for large distributed backend architectures, but has been distributed outtoken
If you want to revoke the permission, it is not very convenient.- SSO Single Sign-On (SSO) is suitable for medium to large enterprises that want to unify the login methods of all their internal products.
- OAuth third-party login, easy to use, friendly to users and developers, but there are many third-party platforms, you need to choose a suitable third-party login platform.
instructions
The above part of the content source and their review when the network search, also mainly used for personal learning, equivalent to the existence of notepad, do not list the link article temporarily. If any author sees it, please contact me to post the link to the original text.