Login is a function that is often used in every website. On the page, we enter the account password, press enter, and log in. But do you know the login principle behind this? Today we will introduce some common login methods.

  • Cookie + Session Login
  • Token login
  • OAuth Third-party login

Cookie + Session Login

HTTP is a stateless protocol. Each time a client sends a request, it first establishes a connection with the server and then disconnects the connection after the request is completed. This method can save connection resources occupied during transmission, but there is also a problem: each request is independent, and the server cannot determine whether the current request and the last request are from the same user, and thus cannot determine the login status of the user.

To solve the problem of HTTP statelessness, Lou Montulli introduced cookies in 1994.

Cookie is a piece of special information sent by the server to the client, which is stored in the form of text on the client, and the client will bring these special information every time it sends a request to the server.

With cookies, the server can get the information passed by the client. If the information needs to be authenticated, Session is also needed.

The client requests the server, and the server allocates a chunk of memory for the request, which is called the Session object.

With cookies and sessions in place, login authentication can be performed.

Cookie + Session implementation process

Cookie + Session login is the most classic login method, which is still used by a large number of enterprises.

When a user logs in for the first time:

  1. The user to accessa.com/pageAAnd enter the password to log in.
  2. After the server verifies that the password is correct, it creates the SessionId and stores it.
  3. The server responds to the HTTP request and writes the SessionId to the Cookie via the set-cookie header.

Server-side sessionids can be stored in many places, such as memory, files, databases, etc.

After the first login, subsequent accesses can be authenticated directly using cookies:

  1. The user to accessa.com/pageBThe Cookie written during the first login will be automatically displayed on the page.
  2. The server compares the SessionId in the Cookie with the SessionId saved on the server.
  3. If they are, authentication succeeds.

Cookie + Session problems exist

Although we completed login authentication using Cookie + Session, there are still some problems:

  • As the server needs to connect to a large number of clients, it needs to store a large number of sessionids, which causes excessive server pressure.
  • If the server is a cluster, the SessionId needs to be synchronized to each machine in order to synchronize the login state, which increases the maintenance cost of the server.
  • Because sessionids are stored in cookies, CSRF attacks cannot be avoided.

Token login

In order to solve many problems exposed by Session + Cookie mechanism, we can use Token login mode.

A Token is a string generated by the server as a Token requested by the client. After you log in to the server for the first time, the server generates a Token and returns it to the client. When the client accesses the server for the first time, the client only needs to carry the Token for identity authentication.

Token mechanism implementation process

When a user logs in for the first time:

  1. The user enters the account password and clicks login.
  2. The server verifies the account password and creates a Token.
  3. The server returns the Token to the client, and the client saves the Token freely.

Follow-up page visit:

  1. The user to accessa.com/pageB“With the Token obtained during the first login.
  2. The server verifies the Token. If the Token is valid, the authentication succeeds.

Features of the Token mechanism

Based on the above case, we can analyze the advantages and disadvantages of Token:

  • There is no need to store tokens on the server side, so there is no pressure on the server side, and even if it is a server cluster, there is no need to increase maintenance costs.
  • Tokens can be stored anywhere on the front end and do not need to be stored in cookies, which improves page security.
  • After a Token is sent, it remains valid within the validity period. It is not easy for the server to revoke the permission of the Token.

Token generation mode

The most common way to generate tokens is to use JWT (Json Web Token), which is a concise, self-contained method for securely passing information between communicating parties in the form of Json objects.

As mentioned above, after the Token is used, the server does not store the Token. How can we determine whether the Token sent by the client is valid?

The answer actually lies in the Token string. In fact, Token is not a random string, but a string composed by a variety of algorithms. Let’s analyze it concretely.

JWT algorithm is mainly divided into three parts: header (header information), Playload (message body), signature (signature).

The header section specifies the signature algorithm used by the JWT:

header = '{"alg":"HS256","typ":"JWT"}'   // 'HS256' indicates that hMAC-SHA256 is used to generate signatures.
Copy the code

The playload section shows the intent of JWT:

payload = '{"loggedInAs":"admin","iat":1422779638}'     // iAT represents the token generation time
Copy the code

The signature part is the signature of JWT. In order to prevent JWT from being tampered with arbitrarily, the signature method is divided into two steps:

  1. The inputbase64urlThe encoded header part,.base64urlThe playload part of the code, which prints unsignedToken.
  2. Enter the server private key, unsignedToken, and output the signature.
const base64Header = encodeBase64(header)
const base64Payload = encodeBase64(payload)
const unsignedToken = `${base64Header}.${base64Payload}`
const key = 'Server Private Key'

signature = HMAC(key, unsignedToken) Copy the code

The final Token calculation is as follows:

const base64Header = encodeBase64(header)
const base64Payload = encodeBase64(payload)
const base64Signature = encodeBase64(signature)

token = `${base64Header}.${base64Payload}.${base64Signature}`
Copy the code

The server determines the Token:

const [base64Header, base64Payload, base64Signature] = token.split('. ')

const signature1 = decodeBase64(base64Signature)
const unsignedToken = `${base64Header}.${base64Payload}`
const signature2 = HMAC('Server Private Key', unsignedToken)
 if(signature1 === signature2) {  return 'Signature verified successfully, token was not tampered with' }  const payload = decodeBase64(base64Payload) if(new Date() - payload.iat < 'Token validity period') { return 'token effective' } Copy the code

With the Token, the login method has become very efficient, so let’s look at two other login methods.


Single sign-on (SSO) refers to setting up a public authentication center within an enterprise. All products can be logged in to in the authentication center. After logging in to the authentication center, a product can access another product and obtain the login status without logging in again.

SSO mechanism implementation process

Users need to log in to the authentication center for the first time:

  1. User access to the sitea.comUnder pageA page.
  2. Because you are not logged in, you are redirected to the authentication authority with the callback addresswww.sso.com?return_uri=a.com/pageASo that you can directly access the corresponding page after login.
  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=123Bring the authorization code ticket and authenticate the centersso.comWrites cookies to the login state of.
  5. ina.comOn the server, hold ticket to the authentication center to confirm that the authorization code ticket is valid.
  6. After the authentication is successful, the server writes the login information into cookies (at this time, the client has two cookies stored respectivelya.comsso.comLogin state).

After logging in to the authentication authority, continue to visit other pages under a.com:

At this time, because a.com has logged in Cookie information, so the server directly successful authentication.

If the authentication authority login is complete, visit the page under b.com:

In this case, the authentication center has a Cookie that you have logged in to before, so you do not need to enter the password again. You can directly return to Step 4 and send ticket to b.com.

SSO SSO exits

So far, we have completed single sign-on, which can be shared by multiple products under the management of the same certification authority. Now we need to think about logging out. That is: if you log out of one product, how do you log out of all the other products?

The principle is not hard to understand. Back to Step 5, when each product authenticates a ticket to a certification authority, it can also send its own logout API to the certification Authority.

When a product c.com logs out:

  1. emptyc.comLogin state Cookie in.
  2. Request authentication Centersso.comThe exit API in.
  3. The authentication center traverses all products that issue ticket and invokes the corresponding API to log out.

OAuth Third-party login

In the above, we use single sign-on to complete the login state sharing of multiple products, but are established in a unified certification center, for some small enterprises, it is too much trouble, is there a login can do out of the box?

In fact, there are, many large factories will provide their own third-party login services, we will analyze it together.

OAuth mechanism implementation process

Here we take the access process of wechat open platform as an example:

  1. First of all,a.comOperators of wechat need to register an account on wechat’s open platform and apply to wechat to use the wechat login function.
  2. After the application is successful, the appID and AppSecret of the application are obtained.
  3. The user ina.comChoose to log in using wechat.
  4. At this time, it will jump to wechat OAuth authorized login, and bringa.comThe callback address of.
  5. Users enter their wechat accounts and passwords. After successful login, they need to select an authorization scope, such as the profile picture and nickname of the authorized user.
  6. After authorization, wechat will pull up according toa.com?code=123“With a temporary ticket code.
  7. After getting the code,a.comWill take the code, appID, appSecret, to the wechat server to apply for a token, after successful verification, wechat will issue a token.
  8. With the token,a.comYou can use the token to get the corresponding wechat account, such as user nicknames and other information.
  9. a.comThe user is prompted for a successful login and writes the login status to Cooke as credentials for subsequent access.


This article introduces four common login methods, the principle should be clear to everyone, summarize the use of these four scenarios:

  • Cookie + Session has a long history and is suitable for simple back-end architectures that require developers to take care of their own security issues.
  • The Token scheme has little pressure on the back end and is suitable for large distributed back end architectures. However, it is not very convenient to revoke permissions for distributed tokens.
  • Single sign-on (SSO) applies to medium – and large-sized enterprises that want to unify the login methods of all 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 their own third-party login platform.