cookie保存后端传来的token值,请求每一个接口header都带上token值

一、后端拦截器,实现每个请求都需要token,没有就要进行拦截

/**
 * 自定义拦截器
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
	@SneakyThrows
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		/*// 设置返回为json格式,使用UTF-8(这部分有问题)
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");*/
		//获取请求头的token
		String token = request.getHeader("token");
		System.out.println("拦截器生成的token是"+token);
		if(token==null){
			throw new ScoreException(400, "token不能为空");
		}
		//在jwt里面验证是否为有效的token
		boolean b = JwtTokenUtil.checkToken(token);
		if(!b){
			throw new ScoreException(400, "token没有效");
		}else{
			return true;
		}

	}
}

二、配置拦截器

package com.lza.scoresys.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * 配置拦截器
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
	@Autowired
	private AuthenticationInterceptor interceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(interceptor)
				.addPathPatterns("/**").excludePathPatterns("/login/**")//放行登陆路径
				.excludePathPatterns("/doc.html/**")
				.excludePathPatterns("swagger/**")
				.excludePathPatterns("/swagger-ui.html")
				.excludePathPatterns("swagger-ui.html")
				.excludePathPatterns("/webjars/**")
				.excludePathPatterns("/swagger-ui.html/*")
				.excludePathPatterns("/swagger-resources")
				.excludePathPatterns("/swagger-resources/**")
				.excludePathPatterns("/v2/**")
				.excludePathPatterns("/employee/**");//放行员工
				//.excludePathPatterns("/student/**");
	}
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		//本应用的所有方法都会去处理跨域请求
		registry.addMapping("/**")
				//允许远端访问的域名
				.allowedOrigins("http://localhost:8080")
				//允许请求的方法("POST", "GET", "PUT", "OPTIONS", "DELETE")
				.allowedMethods("*")
				//允许请求头
				.allowedHeaders("*");

	}
}

三、前端vue引入cookie cnpm install js-cookie

/*//引入cnpm install js-cookie*/
    import cookie from 'js-cookie';

在这里插入图片描述

四、登陆成功后,把后端接口返回的token保存在cookie上

 methods: {
      handleSubmit(who)
      {
        if (who == 1) {
          instance.post('/login/studentLogin',{
              username: this.ruleForm2.username,
              password: this.ruleForm2.password
            }).then(res => {
            console.log(res.data);
            if (res.data.code == 200) {
              alert("登陆成功,返回token是" + res.data.data.token);
              //把token字符串放在cookie里面(第一个参数cookie名称,第二个名称参数值,第三个参数作用范围)
              cookie.set('token', res.data.data.token,{domain:'localhost'});
              this.$router.push({name:'Student'})//跳转到学生路由
            } else {
              alert(res.data.message)
            }
          })

在这里插入图片描述
五:前端拦截器

import axios from "axios";
import cookie from 'js-cookie';
//创建默认实列
const instance=axios.create({
  baseURL:'http://localhost:8084',
  timeout:5000,
});
//拦截器
instance.interceptors.request.use(config=> {
  if (cookie.get('token')) {
    //把获取cookie值放到header里面
    config.headers['token'] = cookie.get('token');
  }
  return config;
},
  error => {
  return Promise.reject(error)
})

//暴露实例出去
export default instance;

在这里插入图片描述
六:运行结果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值