Jwt全称是:json web token。它将用户信息加密到token里,服务器不保存任何用户信息。服务器通过使用保存的密钥验证token的正确性,只要正确即通过验证。
token的用处:当用户第一次登陆后,用户名密码验证成功后,服务器会生成一个token,把token返回到客户端,一般token都是储存在浏览器的localStorage 或 cookies中,存在localStorage的token需要通过js,将token添加到http请求头中,下次再访问服务器,就不需要用户名密码了,只要带上token,服务器验证token的合法性后,就能访问后端资源了。
利用JWT生成token,将userId放进去并加密
static final String SECRET = "X-Litemall-Token";
static final String ISSUSER = "LITEMALL";
static final String SUBJECT = "this is litemall token";
static final String AUDIENCE = "MINIAPP";
public String createToken(Integer userId){
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
Map<String, Object> map = new HashMap<String, Object>();
Date nowDate = new Date();
Date expireDate = getAfterDate(nowDate,0,0,0,2,0,0);
map.put("alg", "HS256");
map.put("typ", "JWT");
String token = JWT.create()
.withHeader(map)
.withClaim("userId", userId)
.withIssuer(ISSUSER)
.withSubject(SUBJECT)
.withAudience(AUDIENCE)
.withIssuedAt(nowDate)
.withExpiresAt(expireDate)
.sign(algorithm);
return token;
} catch (JWTCreationException exception){
exception.printStackTrace();
}
return null;
}
public Integer verifyTokenAndGetUserId(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(ISSUSER)
.build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> claims = jwt.getClaims();
Claim claim = claims.get("userId");
return claim.asInt();
} catch (JWTVerificationException exception){
}
return 0;
}
|