Self-study notes: JWT

JWT

Introduction

jwt (JSON Web Token), json web token. As the name implies, it is a token used for web applications, which is used for verification.

Features of jwt:

  1. Authorization certification
    The most common way to use jwt. After the user logs in, each subsequent request includes the jwt, allowing the user to access the routes, services, and resources allowed by the token. Single sign-on is a feature that is widely used in jwt today because of its low overhead and ease of use.

  2. information exchange

    jwt can transmit information between parties, and can sign it, which can prevent information from being tampered with.

The composition of jwt

It consists of Header, Payload, and Signature. Use "." to separate each part.

  • Header: The header, used to describe the metadata, is a JSON object.

    Usually consists of two parts: the type of token and the signature algorithm used

  • Payload: The payload, claims and data, is also a JSON object.

  • Signature: Signature is the signature of the first two parts (header, payload) to prevent data tampering.
    Use Base64-encoded Header and Payload plus a key (secret, must not be leaked, only the server knows), and then generate a signature according to the signature algorithm specified by the Header (default HMAC SHA256).

    const signature= HMACSHA256(base64.encode(header) + '.' + base64.encode(payload), secret);
    

** Purpose of signature: ** Since both Header and Payload are only base64 encoded, if they are intercepted, the original information of these two parts can be obtained by anti-decoding (so jwt should not store user sensitive information). If the contents of the first two parts are edited and then base64 encoded, the server will calculate a new Signature according to the Header (after editing) and Payload (after editing), and will find the new Signature and the Signature passed by jwt. If it is different, it can be known that the information has been edited. Since the tampering party does not know the key, the Signature cannot be edited correctly.
but! ! ! If the key is leaked, the tampering party will also tamper with the signature content of jwt according to the key, the server will encrypt according to the Header and Payload of jwt and the key, the new Signature and the Signature passed by jwt It will be the same, pass verification. It's dead, there's no help.

In short: the server will generate its own Signature based on the Header and Payload, compare it with the signature of jwt, and judge according to the comparison result.

The difference between jwt and session

**Traditional session authentication method: **Session is a mechanism to record the session state of the server and the client, which needs to store session information on the server. |
As shown below:

**jwt authentication method:** The biggest difference from session is that the token is saved on the client side. The browser side only performs validation.

Getting started with jwt

  1. import dependencies

            <dependency>
                <groupId>com.auth0</groupId>
                <artifactId>java-jwt</artifactId>
                <version>3.4.0</version>
            </dependency>
    
  2. write demo

    public class demo {
        public static void main(String[] args) {
            String jwt = creatJwt();
            System.out.println("jwt:  "+jwt);
            getMessage(jwt);
        }
    
        //generate jwt
        public static String creatJwt(){
            //Set expiration time
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.SECOND,20);//Indicates that it will expire after 20 seconds
    
            String token= JWT.create()
                    .withClaim("userId",111)
                    .withClaim("userName","thoughts")
                    .withExpiresAt(instance.getTime())          //token expiration time
                    .sign(Algorithm.HMAC256("s!i!x!u!"));       //key
            return  token;
        }
    
        //Get information according to jwt
        public static void getMessage(String token){
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("s!i!x!u!")).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            System.out.println(verify.getClaims().get("userId").asInt());       
            System.out.println(verify.getClaims().get("userName").asString());
        }
    }
    
  3. Result test:

Tags: Java Session jwt

Posted by kiwi_uk on Sun, 08 May 2022 13:52:06 +0300