SpringBoot集成JWT
1.引入JWT依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
含有多种的工具类引用的依赖:
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency>
2.TokenUtils
package com.hy.demo.util;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import cn.hutool.core.date.DateUtil;
import com.hy.demo.po.Controller;
import com.hy.demo.service.ControllerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
/**
* @author
*/
@Component
public class TokenUtils {
private static ControllerService staticControllerService;
@Autowired
private ControllerService controllerService;
@PostConstruct
public void ControllerService(){
staticControllerService=controllerService;
}
/**
* 生成token
*
* @return
*/
public static String genToken(String userId, String sign) {
return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
.withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
.sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
}
/**
* 获取当前登录的用户信息
*
* @return
*/
public static Controller getCurrentUser() {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
if (StrUtil.isNotBlank(token)) {
String userId = JWT.decode(token).getAudience().get(0);
return staticControllerService.getById(Integer.valueOf(userId));
}
} catch (Exception e) {
return null;
}
return null;
}
}
token 案例:
{
"cid": 1,
"cname": "胡萝卜",
"cpassword": "123456",
"newPassword": null,
"confirmPassword": null,
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjQ5MDQ2MDgwfQ.C6mesKi60apGN_qqUlJZVbnSp1ifW7zh4qdclEhXobY"
}
3.JWT拦截器实现类
package com.hy.demo.config.interceptor;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.hy.demo.exception.ServiceException;
import com.hy.demo.po.Controller;
import com.hy.demo.service.ControllerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private ControllerService controllerService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
// 执行认证
if (StrUtil.isBlank(token)) {
throw new ServiceException("402", "无token,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new ServiceException("402", "token验证失败,请重新登录");
}
// 根据token中的controllerid查询数据库
Controller controller = controllerService.getById(userId);
if (controller == null) {
throw new ServiceException("402", "用户不存在,请重新登录");
}
// 用户密码加签验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(controller.getCpassword())).build();
try {
jwtVerifier.verify(token); // 验证token
} catch (JWTVerificationException e) {
throw new ServiceException("402","token验证失败,请重新登录");
}
return true;
}
}
4.拦截器配置类
package com.hy.demo.config;
import com.hy.demo.config.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**") // 拦截所有请求,通过判断token是否合法来决定是否需要登录
.excludePathPatterns("/controller/login", "/controller/register")//放行请求
;
}
@Bean
public JwtInterceptor jwtInterceptor(){
return new JwtInterceptor();
}
}
5.登录实现方法
public Result login(ControllerDto controllerDto) {
//判断空
String cname = controllerDto.getCname();
String cpassword = controllerDto.getCpassword();
if(StringUtils.isBlank(cname) || StringUtils.isBlank(cpassword)){
return Result.error("300","参数错误");
}
//获取用户信息
Controller one = getControllerInfo(controllerDto);
if(!Objects.equals(one,null)){
BeanUtil.copyProperties(one,controllerDto,true);
String token = TokenUtils.genToken(one.getCid().toString(), one.getCpassword());//设置token
controllerDto.setToken(token);
return Result.success(controllerDto);
}
return Result.error("300","用户名或者密码错误");
}