1. 导包
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.18.2</version>
</dependency>
2. 在登录用户接口返回token(当用户登录时返回token)
登录接口
@PostMapping("/user-tokens")
public JsonResponse<String> login(@RequestBody User user) throws Exception {
String token = userService.login(user);
return new JsonResponse<>(token);
}
public String login(User user) throws Exception {
// 判断用户登录逻辑
...
//如果用户登录成功,返回token,token基于用户id
String token = TokenUtil.generateToken(user.getId());
return token;
}
public class TokenUtil {
private static final String ISSUER = "签发者";
// 创建token
public static String generateToken(Long userId) throws Exception {
Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(),RSAUtil.getPrivateKey());
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.SECOND,30);
return JWT.create().withKeyId(String.valueOf(userId))
.withIssuer(ISSUER)
.withExpiresAt(calendar.getTime())
.sign(algorithm);
}
}
上面的代码会通过用户id生成一个token,前端可以得到token,然后将token报错在浏览器内存里
然后前端只要发送请求,都会带着token
服务端通过token获取用户信息
@GetMapping()
public User getUserInfo(){
Long userId = userSupport.getCurrentUserId();
User user = userService.getUserInfo(userId);
return user;
}
先通过传过来的heander,得到token
public Long getCurrentUserId(){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String token = requestAttributes.getRequest().getHeader("token");
Long userId = TokenUtil.verifyToken(token);
if(userId < 0){
throw new ConditionException("非法用户");
}
return userId;
}
然后验证token,获得用户id
public class TokenUtil {
private static final String ISSUER = "签发者";
// 验证token
public static Long verifyToken(String token){
try {
Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
String userId = jwt.getKeyId();
return Long.valueOf(userId);
}catch (TokenExpiredException e){
throw new ConditionException("555","token过期!");
}catch (Exception e){
throw new ConditionException("非法token");
}
}
}
最后通过用户id获得用户信息
1. 用户先登录,登录是会判断是否为合法用户,如果是就返回一个token
2. 前端得到token,然后发送请求时会在header携带token
3. 后端从Header的到token,然后通过jwt解析token,成用户id
4. 通过用户Id可以查询时哪个用户