I received an order from the superior last week, and I need to complete the background interface function provided to the APP. The first thing to solve is the token verification. I believe that everyone who can see this article knows what the token is, because in the previous projects, they are all themselves. Handwritten, leave it to me to complete, I will definitely use JJWT for convenience (lazy), just record it here
1. maven dependencies
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency>
2. Create a TokenUtil class and provide methods for creating and obtaining token information
2.1 createToken is mainly to set various values
public String createToken(String strUserId, String strOrgId) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); long ttlMillis = nowMillis + (3600L * 1000L * time); Date now = new Date(nowMillis); Date exp = new Date(ttlMillis); HashMap<String, Object> claims = new HashMap<String, Object>(); claims.put("orgId", strOrgId); JwtBuilder jwtBuilder = Jwts.builder() .setClaims(claims) .setId(id) .setIssuedAt(now) .setExpiration(exp) .setSubject (strUserId) .signWith(signatureAlgorithm, generalKey()); return jwtBuilder.compact(); }
Important note: setClaims, the custom private declaration, must be in front, otherwise it will be overwritten
2.2 getToken
public Claims getToken(String token) throws Exception{ Claims claims = Jwts.parser() .setSigningKey(generalKey()) .parseClaimsJws(token) .getBody(); return claims; }
2.3 Verify token
if(claims != null){ String strUserId = claims.getSubject(); request.setAttribute("userId", strUserId); String strOrgId = claims.get("orgId", String.class); request.setAttribute("orgId", strOrgId); return true; }