JWT technology in session tracking solution - used to implement login authentication

1. Conversation technology
  • Session: The user opens the browser, accesses the resources of the web server, and the session is established until one party disconnects and the session ends. A session can contain multiple requests and responses.
  • Session tracking: A method of maintaining browser state. The server needs to identify whether multiple requests come from the same browser in order to share data between multiple requests in the same session.
        Session tracking solution:
  • Client session tracking technology: Cookies
  • Server-side session tracking technology: Session
  • Token technology
        Advantages and Disadvantages of Each Tracking Plan:
Cookie:

advantage:

  • Simple and easy to use: Cookies are a mechanism built into the browser and are relatively simple to use.
  • Front-end control: It can be easily set and read on the front-end without server involvement, making status tracking in certain scenarios more convenient.

shortcoming:

  • Security: Cookies are stored on the client side and may be tampered with or stolen, so they are not suitable for storing sensitive information.
  • Size limit: There are limits on the number and total size of cookies under each domain name, which may cause insufficient storage problems.
  • Cross-domain issues: Cookies can usually only be used under the domain name where they are set, making it inconvenient to share session information between different domain names.
Session:

advantage:

  • Security: Session data is stored on the server, which is more secure than cookies and can store sensitive information.
  • Flexibility: It can store complex data structures and is suitable for storing session-related data.
  • Cross-domain issues: Session data is stored on the server and therefore can be shared between different domain names.

shortcoming:

  • Storage overhead: Each session needs to store relevant data on the server, which may increase the load on the server.
  • Scalability: External storage or distributed solutions are required to support high load or multi-server environments.
Token technology (such as JWT):

advantage:

  • Stateless: Token technology is based on the principle of stateless. The server does not need to store session data on the back end, and is suitable for distributed architecture.
  • Cross-platform: Tokens can be transferred between different platforms and services, suitable for applications with separate front-end and back-end.
  • Scalability: Customized information can be included in the token to adapt to the needs of various scenarios.

shortcoming:

  • Security: Token tampering may lead to security issues, requiring security measures such as encryption and signatures.
  • Token size: Tokens may be larger than traditional session identifiers (such as Session ID), increasing network transmission overhead.
  • Processing complexity: The validity of the token needs to be verified on the server side, which may require some additional code and operations.
2. JWT technology
1) Full name: JSON Web Token

        Defines a concise, self-contained format for securely transmitting information in json data format between communicating parties. This information is reliable due to the presence of digital signatures.

2) Composition:
  • The first part: Header, records token type, signature algorithm, etc. For example: {"alg":"HS256","type":"JWT")
  • The second part: Payload (payload), carries some custom information, default information, etc. For example: ("id":"1" "username":"Tom")
  • The third part: Signature (signature), prevents Token from being tampered with and ensures security. Add the header, payload, and the specified secret key, and calculate it through the specified signature algorithm.
3) Scenario: Login authentication
  • After successful login, generate a token
  • Each subsequent request must carry a JWT token. Before each request is processed, the system will verify the token and process it after passing it.
 4) JWT generation

Example:

	@Test
	public void testGenJwt(){
		Map<String, Object> clamis = new HashMap<>();
		clamis.put("age",18);
		clamis.put("username","Young");
		String jwt= Jwts.builder()
					.setClaims(clamis)//自定义内容(载荷)
					.signWith(SignatureAlgorithm.HS256,"Young")//签名算法
					.setExpiration(new Date(System.currentTimeMillis() + 3600*1000))//有效期设置为一小时
					.compact();
		System.out.println(jwt);
	}

        In the above code, Jwts.builder(): This is the starting point for the generator that creates the JWT token. It allows you to configure step by step the various parts required to generate a JWT.

        Then declare a claims object, here claimsis the one Map<String, Object>that contains the claims I want to add to the payload of the JWT. In JWT, the payload is a set of key-value pairs that contain information about the token. Then I put the information into clamis.

        And of .signWith(SignatureAlgorithm.HS256, "Young"): This is the part that specifies how to sign the JWT. SignatureAlgorithm.HS256Indicates that the HMAC SHA-256 signature algorithm is used, Youngand is the key used for signing.

  .setExpiration(new Date(System.currentTimeMillis() + expire)): The expiration time of JWT is set here. This is set to 1 hour (number of milliseconds), which is used to specify how long after the current time the JWT will expire.

  .compact(): This step combines the various configurations to generate the final JWT token.

5) JWT parsing

Example:

	@Test
	public void testParseJwt(){
		Claims claims = Jwts.parser()
				.setSigningKey("Young")//此处放入你所设置的签名密钥
				.parseClaimsJws("You JWT")//此处放入生成的jwt密钥
				.getBody();
		System.out.println(claims);
	}

Additional: jwt generation and decoding tool classes:

public class JwtUtils {

    private static String signKey = "Young";
    private static Long expire = 43200000L;//设置有效期为24小时

    /**
     * 生成JWT令牌
     * @param claims JWT第二部分负载 payload 中存储的内容
     * @return
     */
    public static String generateJwt(Map<String, Object> claims){
        String jwt = Jwts.builder()
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, signKey)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .compact();
        return jwt;
    }

    /**
     * 解析JWT令牌
     * @param jwt JWT令牌
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public static Claims parseJWT(String jwt){
        Claims claims = Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }
}

Note that you need to add dependencies:

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

Guess you like

Origin blog.csdn.net/LuoluoluoluoYan/article/details/132316142