JWT and Cookie Management - Aligheri/jwt-owasp-based-starter GitHub Wiki

JWT and Cookie Management

JWT structure

  • subject
  • expiration date
  • issuerID - issuerId represents the issuer (creator) of the JWT
  • .withNotBefore(now) - cannot be used before a specific time.
  • extra claim fingerprint (Cookies hashed value)
  • header claims ("typ , JWT")
  • signing algorithm (HMAC 256)

JWT Generation:

private String generateToken(String username, String issuerId, String userFingerprintHash) {  
    Calendar c = Calendar.getInstance();  
    Date now = c.getTime();  
    c.add(Calendar.HOUR, 24);  
    Date expirationDate = c.getTime();  
  
    Map<String, Object> headerClaims = new HashMap<>();  
    headerClaims.put("typ", "JWT");  
  
    Algorithm algorithm = HMAC256(SECRET_KEY);  
  
    return JWT.create()  
            .withSubject(username)  
            .withExpiresAt(expirationDate)  
            .withIssuer(issuerId)  
            .withNotBefore(now)  
            .withClaim("userFingerprint", userFingerprintHash)  
            .withHeader(headerClaims)  
            .sign(algorithm);  
}

Cookie value (Fingeprint) Generation:

public String createUserFingerprint() {  
    SecureRandom secureRandom = new SecureRandom();  
    byte[] randomFgp = new byte[50];  
    secureRandom.nextBytes(randomFgp);  
    return Hex.encodeHexString(randomFgp);  
}

Cookie configuration:

public void createCookie(HttpServletResponse response, String name, String value, int maxAge, boolean httpOnly) {  
    Cookie cookie = new Cookie(name, value);  
    cookie.setPath("/");  
    cookie.setMaxAge(maxAge);  
    cookie.setHttpOnly(httpOnly);  
    response.addHeader("Set-Cookie", String.format("%s=%s; Path=%s; Max-Age=%d; HttpOnly; SameSite=Lax",  
            cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge()));  
    response.addCookie(cookie);  
}