1.将用户信息存储到localStorage里
localStorage.setItem("user",JSON.stringify(res.data));
2.路由守卫
//路由守卫
router.beforeEach((to,from,next)=> {
if(to.path === '/login'){
next();
}
const user = localStorage.getItem("user");
if(!user && to.path !=='/login'){
return next("/login")
}
next();
})
3.jwt在后端鉴权
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer){
//指定controller统一接口
configurer.addPathPrefix("/api",clazz ->clazz.isAnnotationPresent(RestController.class));
}
}
前端代码
const user = localStorage.getItem("user");
if(user){
config.headers['token'] = JSON.parse(user).token;
}
拦截器
package com.example.common;
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.JWTVerificationException;
import com.example.entity.Admin;
import com.example.exception.CustomException;
import com.example.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
-
拦截器A
*/
@Component
public class JwtInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);@Resource
private AdminService adminService;@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){// 让OPTIONS请求通过 if (request.getMethod().equals("OPTIONS")) { response.setStatus(HttpServletResponse.SC_OK); return true; } // 获取token String token = request.getHeader("token"); if (StrUtil.isBlank(token)){ token = request.getParameter("token"); } // 开始执行认证 if (StrUtil.isBlank(token)){ throw new CustomException("无token,请重新登录"); } // 获取 token 中的adminId String adminId; Admin admin; try { adminId = JWT.decode(token).getAudience().get(0); // 根据token中的userid查询数据库 admin = adminService.findById(Integer.parseInt(adminId)); }catch (Exception e){ String errMsg = "token验证失败,请重新登录"; log.error(errMsg+",token = " + token,e); throw new CustomException(errMsg); } if (admin == null){ throw new CustomException("用户不存在,请重新登录"); } try { JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build(); // 根据token中的userid查询数据库 jwtVerifier.verify(token); }catch (JWTVerificationException e){ throw new CustomException("token验证失败,请重新登录"); } log.info("token验证成功,允许放行"); return true;
}
}