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:

  1. Cookie + SessionThe login
  2. TokenThe login
  3. SSOSingle sign-on (sso)
  4. OAuthThird-party login

So let’s start with Cookie + Session

1. Cookie + Session

HTTPA 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
HTTPThe problem of statelessness, Lou Montulli introduced in 1994
Cookie.
CookieA 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
CookieTo do that. When the user logged in successfully, the login status will generally be recorded
SessionIn 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
CookieIs undoubtedly the most convenient, so we generally will
Session
IdSave to
CookieWhen the server receives the request, it passes the validation
CookieTo determine whether the user is logged in.


At first login:


  1. The user to accesssome.com/pageXAnd enter your password to log in.
  2. After the server verifies that the password is correct, it will be createdSessionId“And save it.
  3. The server side responds to this HTTP request and passesSet-CookieHeader information that willSessionIdwriteCookieIn the.
  4. Server sideSessionIdIt may be stored in many places, such as memory, files, databases, etc.

After the first login is completed, subsequent access can be used directlyCookieAuthenticated:

  1. The user to accessa.com/pageBPage, will automatically bring the first login writtenCookie.
  2. Server-side alignmentCookieIn theSessionIdAnd saved on the server sideSessionIdConsistent.
  3. 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:

  1. Because the server side needs to connect with a large number of clients, it also needs to store a large number ofSessionId, which can cause the server to become overstressed.
  2. If the server side is a cluster, in order to synchronize the login state, you need toSessionIdSynchronize to each machine, virtually increase the maintenance cost of the server.
  3. Due to theSessionIdStored in aCookieSo it can’t be avoidedCSRFAttack.

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:


  1. The user to accesssome.com/pageXEnter your account password and click Login.
  2. Server side to verify the account password is correct, createToken.
  3. The server side willTokenReturns to the client byThe client is free to save.

During subsequent visits:

  1. The user to accesssome.com/pageYBring the one you got the first time you logged inToken.
  2. The server side validates thisToken, 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).

  • headerSection specifies theJWTThe signature algorithm used;
  • playloadIn part to show thatJWTIntentions;
  • signaturePart isJWTIn order to makeJWTIt can’t be tampered with.

Token advantage

  • No storage is required on the server sideToken, so there will be no pressure on the server side, even if the server cluster, there is no need to increase the maintenance cost.
  • TokenI can store it anywhere on the front end, I don’t have to store it inCookieIn, improve the security of the page.

Token is insufficient

  • TokenAfter it is issued, it remains in effect for as long as it is in effect, but if the server wants to recall itTokenThe 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:

  1. User access to the sitea.comUnder thepageAPage.
  2. Because you are not logged in, you are redirected to the Authentication Authority with the callback addresswww.sso.com?return_uri=a.com/pageAIn order to login directly into the corresponding page.
  3. The user enters the account password at the authentication center and submits the login.
  4. The Authentication Authority verifies that the account password is valid and then redirectsa.com?ticket=123With an authorization codeticketAnd will certify the centersso.comLogin state write toCookie.
  5. ina.comOn the server, hold itticketCheck with Certification Authority for the authorization codeticketTrue and effective.
  6. After successful verification, the server writes the login informationCookie(At this point, the client has twoCookieAre therea.comsso.comLogin state of.

After the Authentication Authority login is complete, continue accessa.comOther pages under:

At this point, because
a.comThere is a logged in
CookieMessage, so the server side directly authenticated successfully.

If the Authentication Authority login has completed, accessb.comPage 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.comCan.

How the SSO mechanism is implemented

There are three main ways to implement single sign-on:

  1. The parent domain Cookie
  2. Certification center
  3. 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:

  1. emptyc.comLogin state inCookie.
  2. Request Certification Authoritysso.comThe exitapi.
  3. Certification center traversal issuedticket(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:

  1. WeChat login.
  2. Login on Weibo.
  3. Qq login. And so on…

Here, the access process of WeChat open platform is taken as an example:

  1. First of all,a.comThe operators of WeChat need to register an account on the WeChat open platform and apply to WeChat for using the WeChat login function.
  2. After the application is successful, the applicant obtains the applicationappid,appsecret.
  3. The user ina.comSelect to log in using WeChat on.
  4. This will jump to WeChat OAuth authorized login, and bringa.comThe callback address of.
  5. User input WeChat account and password, login successfully, need to choose the specific scope of authorization, such as: authorized user’s avatar, nickname, etc.
  6. After authorization, WeChat will pull according toa.com?code=123“And took a temporary note with himcode.
  7. To obtaincodeAfter that,a.comWill take acodeappid,appsecret, apply to WeChat servertoken, WeChat will issue one after the verification is successfultoken.
  8. There are thetokenAfter that,a.comYou can rely ontokenGet the corresponding micro credit account like, user nickname and other information.
  9. a.comInform the user of successful login, and write the login statusCookieTo 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 + SessionIt has a long history, lends itself to simple back-end architectures, and requires developers to take care of security issues themselves.
  • TokenThe solution has little pressure on the backend and is suitable for large distributed backend architectures, but has been distributed outtokenIf 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.