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:
User access
a.com/pageA
and enter the password to log in.After the server verifies that the password is correct, it will create a SessionId and save it.
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:
Users access
a.com/pageB
the page, it will automatically take the first write to Cookie's login.The server compares whether the SessionId in the Cookie is consistent with the SessionId stored on the server.
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:
The user enters the account password and clicks to log in.
The server verifies that the account password is correct and creates a Token.
The server returns the Token to the client, and the client freely saves it.
On subsequent page visits:
User access
a.com/pageB
, the first to bring Token acquired at login.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:
Input
base64url
encoded header portion,.
,base64url
playload partially encoded output unsignedToken.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:
The user visits
a.com
the pageA page under the website .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/pageA
so that you can directly enter the corresponding page after logging in.The user enters the account password in the authentication center and submits for login.
Certification center to verify the account password is valid, then redirect
a.com?ticket=123
take Ticket authorization code, and the authentication centersso.com
of the login state write Cookie.In the
a.com
server holding the ticket confirmation to the certification center, the authorization code ticket real and effective.After successful authentication, the server the login information is written Cookie (In this case the client has there are two Cookie
a.com
andsso.com
the login state).
After registration is completed Certification Center, continue to visit a.com
at other pages:
This time, due to the a.com
presence of Cookie information logged, so the server directly to the authentication is successful.
If the registration is completed after the certification center, visit b.com
the 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.com
can.
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.com
when Log:
Empty
c.com
Login Cookie in the state.Request Certification Center
sso.com
exit in the api.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:
First,
a.com
the operator needs to register an account on the WeChat open platform and apply to WeChat to use the WeChat login function.After the application is successful, you will get the applied appid and appsecret.
User in
a.com
the use of micro-channel selection log.Then it will jump OAuth authorization to log micro letter, and bring
a.com
callback address.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.
After authorization, WeChat will be pulled up
a.com?code=123
, and then a temporary ticket code is brought.After obtaining the code, it
a.com
will apply for a token to the WeChat server with the code, appid, and appsecret. After the verification is successful, WeChat will issue a token.With the token,
a.com
you can use the token to get the corresponding WeChat user avatar, user nickname and other information.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