SpringBoot——自定义拦截器校验认证前端token
引言
防止横向越权,前端会传递token信息到header中,后端需要对header进行鉴权验证。
代码
定义token拦截器
@Component
@Slf4j
public class TokenAuthInterceptor implements HandlerInterceptor {
/**
* token认证配置
*/
@Resource
private TokenAuthProperties tokenAuthProperties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info(">>>>>>>>>TokenAuthInterceptor:请求前拦截认证token, 开关:{}>>>>>>>>>>>>>", tokenAuthProperties.getTokenSwitch());
if (!tokenAuthProperties.getTokenSwitch()) {
log.info("no need to auth token.");
return true;
}
String token = request.getHeader("authentication");
if (StringUtils.isBlank(token)) {
log.error("token为空,认证失败!");
throw new Exception("token为空,认证失败!");
}
// token其他验证
... ...
log.info("token: [ {} ], 认证成功!", token);
return true;
}
}
自动配置
@Configuration
public class WebAuthConfig extends WebMvcConfigurationSupport {
@Resource
TokenAuthInterceptor tokenAuthInterceptor;
/**
* addInterceptors
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tokenAuthInterceptor).addPathPatterns("/**");
}
}
获取token的方法
//获取前端token
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//获取请求
HttpServletRequest request = attributes.getRequest();
if (StringUtils.isBlank(request.getHeader(AUTHENTICATION))) {
log.error("获取token失败!错误信息:token为空!");
throw new Exception("获取token失败!错误信息:token为空!");
}
烧不死的鸟就是凤凰