About Token and JWT

Token: authenticated token

When a user attempts to log in and submits a request to the server, if the server passes the authentication, a Token data will be generated and responded to the client. This Token is meaningful data. This client should carry this Token data in every subsequent request. The server identifies the user by parsing this Token!

About Session and Token:

  • Session is the data stored in the memory of the server by default, which will occupy a certain amount of server memory resources, and is not suitable for cluster or distributed systems (although it can be solved by sharing session). The Session ID carried by the client is only unique (theoretically), and has no data meaning
  • The essence of Token is the result of encrypting meaningful data. Each server only needs to have the function of parsing the encrypted data to obtain the information meaning. Theoretically, it does not occupy memory resources and is more suitable for cluster and distributed systems. However, there is a certain risk of being decrypted (the probability is extremely low)

JWT

JSON Web Token is a Token that uses JSON format to represent multiple data It encrypts the user information into the Token, and the server does not save any user information. The server verifies the correctness of JWTToken by using the saved key, and it will pass the verification as long as it is correct. Before using JWT, you need to add relevant dependencies in the project for generating JWT and resolving JWT

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

An original JWT data should contain three parts:

1.Head header: Algorithm & Token type (algorithm and Token type)

{
  "alg": "HS256",
  "typ": "JWT"
}

2.PAYLOAD: the DATA in this part of DATA is user-defined and can be stored into any required DATA on demand.

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  your-256-bit-secret
)

3.VERIFY SIGNATURE

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  your-256-bit-secret
)

JWT generation

Map<String, Object> claims = new HashMap<>();
        claims.put("id", 9527);
        claims.put("name", "LiuLaoShi");
        claims.put("nickname", "JavaCangLaoShi");

        // Expiration time of JWT
        Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 1000);
        System.out.println("Expiration time:" + expiration);

        // Composition of JWT: Header (Header: algorithm and Token type), Payload (Payload), Signature (Signature)
        String jwt = Jwts.builder()
                // Header
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                // Payload
                .setClaims(claims)
                .setExpiration(expiration)
                // Signature
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
        System.out.println("JWT=" + jwt);

JWT parsing

// Note: JWT generated with the same secret key must be used, otherwise the parsing will fail
        // Note: expired JWT cannot be used, otherwise parsing will fail
        // Note: when copying and pasting this JWT, do not take "tail", otherwise the parsing will fail
        // Note: you cannot maliciously modify any character in JWT, otherwise the parsing will fail
        String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiTGl1TGFvU2hpIiwibmlja25hbWUiOiJKYXZhQ2FuZ0xhb1NoaSIsImlkIjo5NTI3LCJleHAiOjE2NjI0NTY3ODN9.32MwkSbDz1ce4EvEKHFMCIjcQFUDZz6hn5MtAYr0njQ";

        Claims claims = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
        Integer id = claims.get("id", Integer.class);
        String name = claims.get("name", String.class);
        String nickname = claims.get("nickname", String.class);
        System.out.println("id = " + id);
        System.out.println("name = " + name);
        System.out.println("nickname = " + nickname);

FAQ

1.JWT authorization process and authentication process:

  • Authorization process
    1. The user requests to log in and brings the user name and password to the authorization center
    2. The authorization center carries the user name and password to the user center to query the user
    3. If the query is correct, generate JWT voucher
    4. Return JWT to the user
  • Authentication process:
    1. The user requests a microservice function and carries JWT
    2. Microservices deliver jwt to authorization center for verification
    3. The authorization center returns the verification result to the micro service
    4. The micro service judges the verification result, success or failure
    5. If it fails, 401 is returned directly
    6. If successful, process the business and return

Tags: Java http server

Posted by pulsedriver on Thu, 08 Sep 2022 02:44:15 +0930