Front-end login, this one is enough

Login is a function often used in every website. On the page, we enter the account password and press the Enter key to log in. Do you know the login principle behind this? Today we will introduce several common login methods.

  • Cookie + Session Login

  • Token login

  • SSO single sign-on

  • OAuth third-party login

Cookie + Session Login

HTTP is a stateless protocol. Each time the 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 the connection resources occupied 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. Login status.

In order to solve the problem of HTTP statelessness, Lou Montulli introduced Cookie in 1994.

A cookie is a piece of special information sent by the server to the client. This information is stored in the client in text form. The client will bring this special information with each request to the server.

With the cookie, the server can obtain the information passed by the client. If the information needs to be verified, the session must be passed.

The client requests the server, and the server will open up a memory space for this request. This is the Session object.

With Cookie and Session, we can perform login authentication.

Cookie + Session implementation process

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

When the user logs in for the first time:

  1. User access a.com/pageAand enter the password to log in.

  2. After the server verifies that the password is correct, it will create a SessionId and save it.

  3. The server responds to this HTTP request and writes the SessionId into the Cookie through the Set-Cookie header information.

The SessionId on the server side may be stored in many places, such as memory, files, databases, etc.

After the first login is completed, subsequent visits can directly use cookies for authentication:

  1. Users access a.com/pageBthe page, it will automatically take the first write to Cookie's login.

  2. The server compares whether the SessionId in the Cookie is consistent with the SessionId stored on the server.

  3. If they are consistent, the authentication is successful.

Problems with Cookie + Session

Although we use Cookie + Session to complete the login verification, there are still some problems:

  • Since the server needs to connect to a large number of clients, it also needs to store a large number of SessionIds, which will cause excessive server pressure.

  • If the server is a cluster, in order to synchronize the login status, the SessionId needs to be synchronized to each machine, which invisibly increases the maintenance cost of the server.

  • Since the SessionId is stored in the Cookie, CSRF attacks cannot be avoided.

Token login

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

Token is a string of strings generated by the server as a token requested by the client. After logging in for the first time, the server will generate a Token and return it to the client. The client only needs to bring this Token to complete identity authentication during subsequent visits.

Token mechanism realization process

When the user logs in for the first time:

  1. The user enters the account password and clicks to log in.

  2. The server verifies that the account password is correct and creates a Token.

  3. The server returns the Token to the client, and the client freely saves it.

On subsequent page visits:

  1. User access a.com/pageB, the first to bring Token acquired at login.

  2. The server verifies the Token. If it is valid, the authentication is successful.

Features of Token mechanism

According to the above case, we can analyze the advantages and disadvantages of Token:

  • The server does not need to store the Token, so it will not cause pressure on the server, even if it is a server cluster, there is no need to increase the maintenance cost.

  • Token can be stored anywhere on the front end, and it does not need to be stored in Cookies, which improves the security of the page.

  • After the Token is issued, it will remain valid as long as it is within the effective time. If the server wants to withdraw the Token's authority, it is not easy.

Token generation method

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

As we mentioned above, after using Token, the server will not store the Token, so how to judge that the Token sent by the client is legal and valid?

The answer is actually in the Token string. In fact, Token is not a string of messy strings, but a string formed by splicing and combining a variety of algorithms. Let's analyze it in detail.

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

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

header = '{"alg":"HS256","typ":"JWT"}'   // `HS256` 表示使用了 HMAC-SHA256 来生成签名。

The playload part indicates the intent of JWT:

payload = '{"loggedInAs":"admin","iat":1422779638}'     //iat 表示令牌生成的时间

The signature part is the signature of the JWT. The main purpose is to prevent the JWT from being tampered with. The signature method is divided into two steps:

  1. Input base64urlencoded header portion, ., base64urlplayload partially encoded output unsignedToken.

  2. Enter the server-side private key, unsignedToken, and output the signature.

const base64Header = encodeBase64(header)
const base64Payload = encodeBase64(payload)
const unsignedToken = `${base64Header}.${base64Payload}`
const key = '服务器私钥'

signature = HMAC(key, unsignedToken)

The final Token is calculated as follows:

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

token = `${base64Header}.${base64Payload}.${base64Signature}`

When the server judges the Token:

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

const signature1 = decodeBase64(base64Signature)
const unsignedToken = `${base64Header}.${base64Payload}`
const signature2 = HMAC('服务器私钥', unsignedToken)

if(signature1 === signature2) {
  return '签名验证成功,token 没有被篡改'
}

const payload =  decodeBase64(base64Payload)
if(new Date() - payload.iat < 'token 有效期'){
  return 'token 有效'
}

With Token, the login method has become very efficient. Next, we introduce the other two login methods.

SSO single sign-on

Single sign-on refers to the establishment of a public certification center within the company. The login of all products under the company can be completed in the certification center. After a product is logged in to the certification center, you can visit another product without logging in again. To get the login status.

SSO mechanism implementation process

When the user visits for the first time, he needs to log in at the authentication center:

  1. The user visits a.comthe pageA page under the website   .

  2. Since you are not logged in, you will be redirected to the certification center with the callback address www.sso.com?return_uri=a.com/pageAso that you can directly enter the corresponding page after logging in.

  3. The user enters the account password in the authentication center and submits for login.

  4. Certification center to verify the account password is valid, then redirect   a.com?ticket=123take Ticket authorization code, and the authentication center sso.comof the login state write Cookie.

  5. In the a.comserver holding the ticket confirmation to the certification center, the authorization code ticket real and effective.

  6. After successful authentication, the server the login information is written Cookie (In this case the client has there are two Cookie a.comand sso.comthe login state).


After registration is completed Certification Center, continue to visit a.comat other pages:

This time, due to the a.compresence of Cookie information logged, so the server directly to the authentication is successful.


If the registration is completed after the certification center, visit b.comthe next page:

This time, due to the presence of previously logged Cookie certification center, so they do not re-enter the account password, direct return to step 4, issued a ticket to the b.comcan.

SSO single sign-on logout

At present, we have completed single sign-on. Under the management of the same certification center, multiple products can share the login state. Now we need to consider logging out, that is: log out in one product, how to make other products also log out?

The principle is actually not difficult. You can go back and look at Step 5. When each product verifies the ticket with the certification center, it can actually send its logout api to the certification center.

When a product c.comwhen Log:

  1. Empty c.comLogin Cookie in the state.

  2. Request Certification Center sso.comexit in the api.

  3. The certification center traverses all the products that have issued the ticket, and calls the corresponding exit api to complete the exit.

OAuth third-party login

In the above, we have used single sign-on to complete the login status sharing of multiple products, but they are all based on a unified certification center. For some small enterprises, it is too troublesome. Is there a login that can be done out of the box? Ready to use?

In fact, yes, many major manufacturers provide their own third-party login services. Let's analyze it together.

OAuth mechanism implementation process

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

  1. First, a.comthe operator needs to register an account on the WeChat open platform and apply to WeChat to use the WeChat login function.

  2. After the application is successful, you will get the applied appid and appsecret.

  3. User in a.comthe use of micro-channel selection log.

  4. Then it will jump OAuth authorization to log micro letter, and bring a.comcallback address.

  5. The user enters the WeChat account and password. After successfully logging in, you need to select the specific authorization scope, such as the avatar and nickname of the authorized user.

  6. After authorization, WeChat will be pulled up a.com?code=123, and then a temporary ticket code is brought.

  7. After obtaining the code, it a.comwill apply for a token to the WeChat server with the code, appid, and appsecret. After the verification is successful, WeChat will issue a token.

  8. With the token, a.comyou can use the token to get the corresponding WeChat user avatar, user nickname and other information.

  9. a.com The user is prompted to log in successfully, and the login status is written to Cooke as a credential for subsequent visits.

to sum up

This article introduces 4 common login methods, the principles should be clear to everyone, and summarize the usage scenarios of these 4 solutions:

  • Cookie + Session has a long history and is suitable for a simple back-end architecture. Developers need to handle security issues themselves.

  • The Token scheme has low pressure on the back-end and is suitable for large-scale distributed back-end architectures, but the distributed tokens are not very convenient if they want to withdraw their permissions.

  • SSO single sign-on is suitable for medium and large enterprises who want to unify the login methods of all internal products.

  • OAuth third-party login is simple and easy to use, friendly to users and developers, but there are many third-party platforms, and you need to choose your own third-party login platform.


"Watching and forwarding" is the greatest support

Guess you like

Origin blog.csdn.net/liuyan19891230/article/details/108138540