Cookies Session JWT

Cookies

Cookies are a type of session tracking technology that achieves the effect of sharing data between sessions by saving data to the client’s browser.

The moment you open the browser and start accessing the page until you close the browser and disconnect is counted as a session. A session can contain multiple requests and responses. Each request response is stateless, which means that the server cannot know what happened in the previous request through this request.

Cookies implementation principle:

  1. The browser sends a request to the server -> the server responds to the request (carrying the set-cookies response header)

    2. When the browser sends a request to the server again, it will carry the current browser’s cookie information in the request header.

Cookies advantages and disadvantages:

Advantages: HTTP protocol is supported by default
Disadvantages: 1. Cross-domain cannot be performed 2. Cookies are always unsafe data, users can disable Cookies 3. Mobile terminal is not available

Cross-domain: As long as the domain name, IP, and port number have a different link, they are considered cross-domain.

java implementation

Obtain response/request information through HttpServletResponse and HttpServletRequest, set cookies in the response information, and obtain all cookies of the browser in the request information.

@RestController
public class SessionController {<!-- -->
    @GetMapping("/setCookies")
    public String setCookies(HttpServletResponse response){<!-- -->
        response.addCookie(new Cookie("name","yi"));
        return "ok";
    }
    @GetMapping("/getCookies")
    public String getCookies(HttpServletRequest request){<!-- -->

        Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){<!-- -->
            System.out.println(cookie.getName() + ":" + cookie.getValue());
        }
        return "ok";
    }
}

Session


Session is implemented based on Cookies and is also a session tracking technology.
The difference between Session and Cookies is that Session stores information on the server to form a Session object instead of in the browser.

Session principle:

  1. When the browser sends the first request to the server, the server will generate a unique Session object and respond to the browser with the ID of the Session object by setting cookies, so that the next browser request will carry cookies containing the SessionID. information.

  2. When the browser makes a second request, the server can find the corresponding Session object through the SessionID carried in the request, thereby knowing what information is stored in this session.

Session advantages and disadvantages:

Advantages: stored on the server, data is relatively secure
Disadvantages: 1. It cannot be used under a server cluster, 2. It is based on Cookies and contains all the disadvantages of Cookies.

java implementation:

When the parameter is HttpSession, the program will automatically determine whether the current request has a corresponding session object. If not, create a new HttpSession object and add set-cookies:SessionId… to the response header.
getSession is equivalent to getSession2 and can obtain the Session object from HttpServletRequest.

@GetMapping("/setSession")
    public String setSession(HttpSession session){<!-- -->
        System.out.println(session.hashCode());
        session.setAttribute("name","li");
        return "OK";
    }

    @GetMapping("/getSession")
    public String getSession(HttpSession session){<!-- -->
        System.out.println(session.hashCode());
        System.out.println(session.getAttribute("name"));
        return "OK";
    }
    @GetMapping("/getSession2")
    public String getSession2(HttpServletRequest request){<!-- -->
        HttpSession session = request.getSession();
        System.out.println(session.hashCode());
        System.out.println(session.getAttribute("name"));
        return "OK";
    }

JWT token technology (Json Web Token)

When the client browser makes the first request (such as successful login), the server generates a token (a string) and returns it to the browser through the response. The browser can store the received token anywhere.
The token is carried in every subsequent request, and the server will verify the token in the request and return the corresponding result.

JWT composition format:

The first part: Header (header), records token type and signature algorithm
The second part: Payload (payload), carries custom information. The message terminology inside is called Claims
The third part: Signature (signature), combines header, payload and adds the specified secret key, calculated through the signature algorithm

Advantages and disadvantages:

Advantages: Supports PC mobile terminals, solves cluster environment certification issues, reduces server storage pressure,
Disadvantages: Need to implement it yourself

java implementation:

  1. Introduce maven dependencies
 <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-gson</artifactId>
            <version>0.11.2</version>
        </dependency>

//Just write the secret key
  String secret="4wAJAxLrSdtgJC8G2jsC/IcJMPfAp + a3IHJBYZkufYCQdh2Afk1TeHRgSwX/fEXHBGaP8mftoUiSd22G93GJ5A==";
//Generate JWT String and pass in the payload through the claims parameter
    public String GenJWT(Map<String,Object> claims){<!-- -->

        String jwt = Jwts.builder().signWith(SignatureAlgorithm.HS256, secret)//Signature algorithm secret key
                .setClaims(claims)//Specify payload (custom data)
                .setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000))//1 hour expiration
                .compact();
        return jwt;
    }

    public void ParseJWT(String jwt) {<!-- -->
        try {<!-- -->
            Claims body = Jwts.parser()
                    .setSigningKey(secret) //Set the secret key
                    .parseClaimsJws(jwt) //Fill in the jwt to be parsed
                    .getBody(); //Get custom data
            System.out.println(body);
            System.out.println("parsing successful");
        } catch (Exception e){<!-- -->
            System.out.println("Parsing failed, tampered with");
        }
    }
    @Test
    public void testJWT() throws InterruptedException {<!-- -->
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("name","li");
        String jwt= GenJWT(claims);

        System.out.println(jwt);
        ParseJWT(jwt);
    }