I. Maintenance and drawbacks of session state
(1) When a user accesses the server using the user name and password through the browser for the first time, the server authenticates the user name and password.
(2) After the authentication is successful, the session data is generated and saved on the server, and the sessionId is returned to the browser through the cookie. The browser records the sessionId in the cookie.
(3) When the browser visits again, it will carry the sessionId in the cookie by default. The server verifies that the sessionId exists or is valid. If the sessionId exists, the current session will be maintained without re-login and the data required by the browser will be returned.
Benefits:
The main implementation of session is as follows: After a user logs in, the session information is retained so that different pages do not need to be logged in again.
If the session times out, or the server restarts (if the session is in service memory), the user is required to log in again, which is where automatic logins come in.
Disadvantages:
1. Generally, sessions are stored in memory. If there are too many users, the memory overhead will be high.
2, there are security problems, CSRF cross-site forgery request attack.
Session is used to identify users based on cookies. If cookies are intercepted, users are vulnerable to cross-site request forgery.
3. Poor scalability, unable to directly support distributed service deployment.
Later, session ids were centrally stored in one place (Redis /memcache) where all machines could access the data, but this increased the possibility of a single point of failure. If the session machine died, everyone would have to log in again, probably getting yelled at. There are also attempts to cluster this single point machine to increase reliability, but in any case, this small session is a heavy burden for me.
Token authentication mechanism
(1) After the client logs in successfully, the server encrypts the userId. The encrypted string is returned to the client as a token along with the userId for verification, but the server does not save the token.
(2) The client can store tokens through cookies, sessionStorage or localStorage.
(3) The client does not carry Authorization by default when it requests again. It needs to add Authorization and carry token information in the request header. If the calculated signature is the same as the signature brought, we know that the user has logged in and can directly get the user ID. If not, the data part must have been tampered with. I will tell the sender: Sorry, there is no authentication.
The data in the Token is in clear text (although I do Base64 encoding, it’s not encrypted) and can still be seen by others, so I can’t store sensitive information like passwords in it.
Of course, if a person’s token is stolen by others, I can’t help it. I will also think that the thief is a legitimate user, which is actually the same as a person’s session ID is stolen by others.
In this way, INSTEAD of saving the session ID, I just generated the token and verified the token, and I used my CPU computing time to get my session storage space!
Relieved of the burden of session ids, my cluster of machines can now easily scale horizontally, increasing user visits and simply adding machines. This feeling of statelessness is so good!
The origin of the Token
Before introducing the principles and advantages of token-based authentication, let’s take a look at what has been done before.
Server-based authentication
We all know that the HTTP protocol is stateless, which means that the program needs to verify every request to identify the client.
Until now, applications have identified requests based on login information stored on the server. This is usually done by storing sessions.
With the rise of the Web, applications, and mobile, this approach to validation is becoming increasingly problematic. Especially in terms of scalability.
Some issues exposed by server-based authentication
1.Seesion: Each time an authentication user initiates a request, the server needs to create a record to store information. As more and more users make requests, the memory overhead increases.
2. Scalability: Seesion is used to store login information in the server memory, which brings scalability problems.
3.CORS(Cross-domain resource sharing) : When we need to use data across multiple mobile devices, cross-domain resource sharing will be a headache. When using Ajax to fetch resources from another domain, requests can be disabled.
4.CSRF(Cross-site request forgery) : when users visit bank websites, they are vulnerable to cross-site request forgery and can be used to access other websites.
Of these, extensible rows are the most prominent. Therefore, it is necessary for us to seek a more effective method.
Token-based authentication principle
Token-based authentication is stateless and we do not store user information in the server or Session.
This concept solves many problems when storing information on the server side
NoSession means that your application can add and subtract machines as needed without worrying about whether the user is logged in or not.
Token-based authentication is performed as follows:
1. The user sends a request using the user name and password.
2. Program verification.
3. The program returns a signed token to the client.
4. The client stores tokens and uses them to send requests each time.
5. The server verifies the token and returns data.
Each request requires a token. The token should be sent in the HTTP header to ensure that the HTTP request is stateless. We also set access-Control-allow-Origin :* to Allow the server to receive requests from all domains. It is important that certificates such as HTTP authentication, client SSL certificates and cookies are not included in the ACAO header marked (designating)*.
Implementation idea:
1. After the verification succeeds, the user returns the Token to the client.
2. The client saves the received data on the client
3. Each time the client accesses the API, it carries a Token to the server.
4. Verify the filter on the server. If the verification succeeds, the request data is returned; if the verification fails, an error code is returned
Once we authenticate the information in the program and get the token, we can do a lot of things with that token.
We can even create a permisse-based token and pass it to third party applications that can access our data (only with specific tokens we allow of course).
The advantages of Tokens
Stateless, server extensible
Tokens stored on the client side are stateless and scalable. Based on this statelessness and not storing Session information, the load balancer can transfer user information from one service to another.
security
Sending tokens instead of cookies in a request prevents CSRF(cross-site request forgery). Even if a cookie is used to store tokens on the client side, the cookie is only a storage mechanism and is not used for authentication. By not storing information in the Session, we have less access to the Session.
Tokens are time-limited and users need to re-verify them after a certain period of time. We also don’t have to wait until the token is automatically invalidated. There is a withdrawal of the token. Token revocataion can invalidate a particular token or a group of tokens that have the same authentication.
extensible
Tokens creates programs that share permissions with other programs. With Tokens, you can provide optional permissions to third party applications. When users want another application to access their data, we can create tokens with special permissions by building our own API.
Multiple platforms cross domains
Let’s start by talking about CORS(Cross-domain resource Sharing), which involves a wide variety of devices and applications when extending applications and services.
Having our API just serve data, we can also make the design choice to serve assets from a CDN. This eliminates the issues that CORS brings up after we set a quick header configuration for our application.
As long as the user has an authenticated token, data and resources can be requested in any domain.
Access-Control-Allow-Origin: *
Copy the code
When creating tokens based on standards, you can set some options. We will describe it in more detail in future articles, but the standard usage will be reflected in JSON Web Tokens.
Recent programs and documentation are available for JSON Web Tokens. It supports numerous languages. This means that you can actually switch your authentication mechanism in the future.