rceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
@Slf4j
public class LoginJWTInterceptor implements HandlerInterceptor {
private static final String ERROR_CODE_401 = "401";
@Autowired
private AdminService adminService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//这里是判断浏览器请求头里的token
String token = request.getHeader("token");
if (StrUtil.isBlank(token)) {
token = request.getParameter("token");
}
// 执行认证
if (StrUtil.isBlank(token)) {
throw new ServiceException(ERROR_CODE_401, "无token,请重新登录");
}
// 获取 token 中的adminId
String adminId;
Admin admin;
try {
adminId = JWT.decode(token).getAudience().get(0);
// 根据token中的userid查询数据库
admin = adminService.getById(Integer.parseInt(adminId));
} catch (Exception e) {
String errMsg = "token验证失败,请重新登录";
log.error(errMsg + ", token=" + token, e);
throw new ServiceException(ERROR_CODE_401, errMsg);
}
if (admin == null) {
throw new ServiceException(ERROR_CODE_401, "用户不存在,请重新登录");
}
try {
// 用户密码加签验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
jwtVerifier.verify(token); // 验证token
} catch (JWTVerificationException e) {
throw new ServiceException(ERROR_CODE_401, "token验证失败,请重新登录");
}
return true;
}
}
在WebConfig配置类中添加自定义拦截器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginJWTInterceptor loginJWTInterceptor;
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 指定controller统一的接口前缀
configurer.addPathPrefix("/api", clazz -> clazz.isAnnotationPresent(RestController.class));
}
// 加自定义拦截器JwtInterceptor,设置拦截规则
//.excludePathPatterns("/api/admin/login");放开登录接口,因为登录的时候还没有token
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginJWTInterceptor) // 添加所有路径需要校验
.addPathPatterns("/api/**").excludePathPatterns("/api/admin/login", "/api/admin/register");//不需要拦截的接口
}
}
设置自定义头配置(前端在request拦截器设置自定义头)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CrosConfiguration {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new U