使用java-jwt
创建和解析JWT,可以使用如下依赖:
1 2 3 4 5
| <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.3.0</version> </dependency>
|
创建token
1 2 3 4 5 6 7 8
| public String createToken(String name, String userId, String email) throws IllegalArgumentException, UnsupportedEncodingException{ JWTCreator.Builder builder = JWT.create(); Algorithm algorithm = Algorithm.HMAC256("xxxxx"); String token = builder.withClaim("name", name.withClaim("user_id", userId).withClaim("email", email) .withExpiresAt(new Date(new Date().getTime() + 24*3600*1000)).sign(algorithm); return token; }
|
解析token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public User parseJwt(String token){ User = new User(); try { Algorithm algorithm = Algorithm.HMAC256("xxxxx"); JWTVerifier verifier = JWT.require(algorithm).acceptExpiresAt(5).build(); DecodedJWT jwt = verifier.verify(token); String userId = jwt.getClaim("user_id").asString(); String name = jwt.getClaim("name").asString(); String email = jwt.getClaim("email").asString(); user.setId(userId); user.setName(name); user.setEmail(email); } catch (JWTVerificationException | IllegalArgumentException | UnsupportedEncodingException e) { log.error("无效的token" + token, e); return null; } catch (Throwable e) { log.error("验证token异常:" + token, e); return null; } return user; }
|
上面是用了相同的密码做的签名,也可以用RSA的公钥私钥。