up:: JWT的原理

说明:

本篇博客主要内容是将session验证升级为JWT认证,主要部分是登陆时的校验,还会演示修改JWT信息时产生的后果以及探讨登出的思路

正式开发

1. 引入依赖,生成JWT

 
<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>3.14.0</version>
</dependency>
 

2.修改登陆的UserController

1.用户登陆时生成JWT

@GetMapping("/loginWithJwt")
@ResponseBody
public ApiRestResponse loginWithJwt(@RequestParam String userName, @RequestParam String password) {
    if (StringUtils.isEmpty(userName)) {
        return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_USER_NAME);
    }
    if (StringUtils.isEmpty(password)) {
        return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_PASSWORD);
    }
    User user = userService.login(userName, password);
    //保存用户信息时,不保存密码
    user.setPassword(null);
    Algorithm algorithm = Algorithm.HMAC256(Constant.JWT_KEY);
    String token = JWT.create()
            .withClaim(Constant.USER_NAME, user.getUsername())
            .withClaim(Constant.USER_ID, user.getId())
            .withClaim(Constant.USER_ROLE, user.getRole())
            //过期时间
            .withExpiresAt(new Date(System.currentTimeMillis() + Constant.EXPIRE_TIME))
            .sign(algorithm);
    return ApiRestResponse.success(token);
}

说明:

Constant.java文件添加常量;

public static final String JWT_KEY = "imooc-mall";
public static final String JWT_TOKEN = "jwt_token";
public static final String USER_ID = "user_id";
public static final String USER_NAME = "user_name";
public static final String USER_ROLE = "user_role";
public static final Long EXPIRE_TIME = 60 * 1000 * 60 * 24 * 1000L;//单位是毫秒