1.导入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
2.编写genToken方法
public static String genToken(String userId,String sign){
return JWT.create().withAudience(userId) //userId作为载
.withExpiresAt(DateUtil.offsetHour(new Date(),2))//两小时后token过期
.sign(Algorithm.HMAC256(sign));//password作为密钥
}
3.将token注入返回数据中
@Override
public UserDTO login(UserDTO userDTO) {
User one = getUserInfo(userDTO);
if(one != null){
BeanUtil.copyProperties(one,userDTO,true);
String token = TokenUtils.genToken(one.getId().toString(),one.getPassword());
userDTO.setToken(token);//设置token
return userDTO;
}else{
throw new ServiceException(Constants.CODE_600,"用户名或密码错误");//抛出自定义异常
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/64d5fb0fd2e47129f9788571e157f7d2.png)
4.将token设置为标头
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null
if(user){
config.headers['token'] = user.token; // 设置请求头
}
return config
}, error => {
return Promise.reject(error)
});
![](https://i-blog.csdnimg.cn/blog_migrate/a5c7e64eb6ceb7067652d5279f3f63d9.png)
5.编写拦截器
package com.cq.springboot.config.inteceptor;
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.cq.springboot.common.Constants;
import com.cq.springboot.entity.User;
import com.cq.springboot.exception.ServiceException;
import com.cq.springboot.service.IUserService;
import com.cq.springboot.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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 IUserService iUserService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
if(StrUtil.isBlank(token)){
throw new ServiceException(Constants.CODE_401,"无token,请重新登录");
}
String userId;
try{
userId = JWT.decode(token).getAudience().get(0);
}catch (JWTDecodeException j){
throw new ServiceException(Constants.CODE_401,"权限认证失败,请重新登录");
}
User user = iUserService.getById(userId);
if(user == null){
throw new ServiceException(Constants.CODE_401,"用户不存在,请重新登录");
}
// 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new ServiceException(Constants.CODE_401,"token认证失败,请重新登录");
}
return true;
}
}
6.配置拦截器
package com.cq.springboot.config;
import com.cq.springboot.config.inteceptor.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("/**")
.excludePathPatterns("/user/login","user/register");
}
@Bean
public JwtInterceptor jwtInterceptor() {
return new JwtInterceptor();
}
}