前端添加请求拦截器
import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$axios = axios
// axios.defaults.baseURL = 'http://localhost:5004/api';
axios.defaults.headers.common['token'] =sessionStorage.token;
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.put['Content-Type'] = 'application/json';
// 添加请求拦截器
axios.interceptors.request.use(function(config) {
config.headers.token =sessionStorage.token;
console.info(sessionStorage.token);
return config;
}, function(error) {
return Promise.reject(error);
});
export default axios
后端
注解passtoken是必须的,因为登录不可能有token拦截
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
UserRepository userRepository;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String token = request.getHeader("token");// 从 http 请求头中取出 token
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
HandlerMethod handlerMethod=(HandlerMethod)handler;
Method method=handlerMethod.getMethod();
//检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
String userId = JWT.decode(token).getAudience().get(0);
try{
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(
userRepository.findById(Integer.parseInt(userId)).get().getPassword())
).build();
jwtVerifier.verify(token);
}catch (JWTVerificationException e){
}
return true;
}
}
然后需要注册到springboot中
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/**"); // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
}
WebMvcConfigurer:拦截器的注册类
HandlerInterceptorAdapter:拦截组件