一、后端拦截器,实现每个请求都需要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;
六:运行结果