Today we talk about a more basic topic, is to achieve the login of the way what? Suitable for new friends.
Session of Huashan
Session, called Session control, is a solution to maintain Session state on the server side. Generally speaking, when the client accesses the server, it stores the corresponding information on the server, generates a Session ID and returns it to the client. When the client visits the server next time, it carries the Session ID so that it can identify the identity of the visitor.
Cookie is a mechanism for the client to save user information. In the browser environment, the request will automatically carry the Cookie information, so that the server can obtain the Session ID.
When the logon logic is implemented on the back end, the HttpSession object is obtained and setAttribute() is used to set the logon user information, such as the user ID. When verifying login, getAttribute() is used to obtain the corresponding Session information. If the information is not obtained, it indicates that the login has not occurred or the Session is invalid.
For Containers such as Tomcat and Jetty, Session is a piece of memory space opened in the server, and the storage structure is Map.
Tomcat’s Session implementation class is StandardSession.
Distributed Session solution
If your application is deployed on a single node, this scenario is fine using the Session mechanism implemented by the Web container. Sessions need to be distributed when there is too much pressure to deploy multiple nodes.
As shown in the figure below, when two Tomcats are deployed, the first request is forwarded to Tomcat1 for load balancing through Nginx, and Session information is stored on Tomcat1. The second request is forwarded to Tomcat2, but Tomcat2 does not have the previous Session information, which is the problem with multi-node Session.
Session replication
Tomcat has a built-in Session replication function, which means that your Session is generated in Tomcat1, and Tomcat1 will synchronize your Session to Tomcat2, so that when your request is sent to Tomcat2, I’ll know who you are.
This approach is often seen in other frameworks, such as the Eureka registry in the Spring Cloud architecture, which also uses replication to synchronize registry information.
For details about Tomcat Session replication configurations, see the official document tomcat.apache.org/tomcat-8.0-…
Sticky session
Sticky sessions mean that requests from the same user are always forwarded to only one instance of Tocmat, so that there is no problem even if there is no Session replication. If a node fails, the access fails.
Common methods include Hash forwarding of IP addresses, which are unreliable because they change. Nginx has a third party module called nginx-sticky- Module that adds a sticky Cookie that is always forwarded to the same server.
The nginx-sticky- Module will record a value in the Cookie to identify the node to which the current request needs to be forwarded. If the request is not forwarded for the first time, the nginx-sticky- Module will forward the request first and write the Cookie before sending the response to the client. The subsequent requests will find the corresponding identifier in the Cookie and then forward to the fixed node.
Session Centralized storage
Session replication occupies server resources and affects performance. Sticky sessions have single point of failure risks. A better distributed Session is centralized storage.
Centralized storage means that session information is stored in a unified place. Web servers such as Tomcat do not store session information. In this way, back-end services are stateless and easy to expand at any time.
As for the implementation of the solution, there are many, you can implement their own HttpSession to do the corresponding storage read logic, can also use open source solutions. For example, Spring Session is a good open source solution, which is easy to use and supports a variety of storage methods, such as Redis and Mysql.
If you are interested in writing Spring Session principles, you can also refer to my previous set of courses: cxytiandi.com/course/5
Shaolin’s Token is unlearned
Token authentication is one of the mainstream authentication methods. The biggest advantage of Token is that it is stateless and does not store session information. This means that the Token can be used to know who is currently accessing the user, without having to retrieve it from the memory of the Web container or from the storage of the centrally managed session.
The Token can be generated in various ways. You can define a fixed format. For example, the Token contains user ID, user name and other information. You can also use the current mainstream JWT approach.
JWT (JSON Web Token) is an open jSON-based standard implemented to deliver declarations in network application environments. JWT declarations are typically used to pass authenticated user identity information between the identity provider and the service provider in order to obtain resources from the resource server.
For example, when a user logs in, the basic idea is that the user provides the user name and password to the authentication server, which verifies the validity of the information submitted by the user. If the authentication is successful, a Token is generated and returned, and the server can identify the request with the Token.
JWT is made up of three parts,
- The first part is the Header;
- The second part is the Payload.
- The third part is Signature.
A JWT-generated Token is in the following format:
token = encodeBase64(header) + ‘.’ + encodeBase64(payload) + ‘.’ + encodeBase64(signature)
The header information usually consists of two parts, the type of token and the signature algorithm used, such as the following code:
{ “alg”: “HS256”, “typ”: “JWT” }
The message body can carry some information required by the application, such as the user ID, as follows:
{ “id”: “1001”, “name”: “yinjihuan”}
The signature is used to determine whether the message has been tampered with on the transmission path to ensure data security. The format is as follows:
HMACSHA256( base64UrlEncode(header) + “.” + base64UrlEncode(payload), secret)
These three parts form our JSON Web Token.
For details, see Github: github.com/jwtk/jjwt
As shown in the figure above: After the request arrives at Tomcat, a separate Token service can be invoked for Token generation, or the Token generation logic can be encapsulated into a JAR package for use. Note That if the embedded mode is used, the encryption configurations of the corresponding tokens must be consistent; otherwise, the authentication fails.
The disadvantage of Token is that it cannot be actively invalidated. For example, in the scenario where Session is used, the user logs out and directly deletes the Session information on the server. Even if the same Session information is used in subsequent requests, the server cannot find the corresponding information.
Token is an encrypted string that contains the user’s information, encryption algorithm, and expiration time. If the expiration time is set to a long time, it means that it can be used before the expiration time.
If the logout function is to be implemented, the expiration time of the Token itself cannot be changed. Therefore, a blacklist mechanism can be used to filter the Token. Store the logged out Token, use the place to match whether logged out, and then intercept it.
About the author: Yin Jihuan, a simple technology lover, the author of Spring Cloud Micro-service – Full stack Technology and Case Analysis, Spring Cloud Micro-service Introduction combat and Progress, the founder of the public account Monkey World.
I have organized a very complete learning material. If you are interested, you can search “Monkey World” on wechat and reply to the keyword “learning material” to obtain the Spring Cloud, Spring Cloud Alibaba, Sharing-JDBC sub-library sub-table and task scheduling framework XXL-job that I have organized. MongoDB, crawler and other related information.