参考:https://www.cnblogs.com/shihaiming/p/9565835.html
使用token鉴权需要引入依赖jar包
一、pom
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4.0</version> </dependency>
二、controller层代码
登录和判断登录
@PostMapping("/login2") public BaseResponse<String> login2(@RequestParam String username, @RequestParam String password) { String token = userService.doLogin2(username, password); return BaseResultUtils.success(token); } @GetMapping("/isLogin2") public BaseResponse<String> isLogin2(HttpServletRequest request){ String token = request.getHeader("token"); if (token == null) { return BaseResultUtils.error(ERROR6); } String username = JWT.decode(token).getAudience().get(0); User user = userService.getUser(username); if (user == null) { return BaseResultUtils.error(ERROR6); } else { JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build(); try { jwtVerifier.verify(token); } catch (JWTVerificationException e) { return BaseResultUtils.error(ERROR6); } return BaseResultUtils.success(true); } }
三、service层代码
@Override public String doLogin2(String username, String password) { User user = userMapper.select(username); if (user != null && user.getPassword().equals(password)) { return user.getToken(user); } else { throw new LoginFailureException(); } }
四、model层代码
在user类中,加入getToken方法
public String getToken(User user) { return JWT.create().withAudience(user.getUsername()) .sign(Algorithm.HMAC256(user.getPassword())); }
测试登录,登录成功即可返回token
测试是否登录,传入token即可通过鉴权