关于vue中token的保存和使用

前端添加请求拦截器

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:拦截组件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值