1 使用:
1.1 新建拦截器类并且实现 HandlerInterceptor 接口
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {
// 注入redis(注意这个注入自己项目封装的redis bean)
@Autowired
private RedisUtil redisUtil;
// nacos 配置中心配置是否开启token 校验(配置自己配置中心里的是否开启验证)
@Value(value = "${token.enable:false}")
private Boolean tokenEnable;
// nacos 配置中心配置是否开启token 校验(配置自己配置中心里的是否开启验证)
@Value(value = "${token.skip-urls-pattern:/noToken}")
private String skipUrlsPattern;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// not token
String uri = request.getRequestURI();
if (!tokenEnable || uri.contains(skipUrlsPattern)){
// 没有开启校验,或者访问url 是免校验的直接放行
return true;
}
// 设置response 的返回数据为json 数据编码为utf-8
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// 本身鉴权逻辑实现 开始验证,验证不通过这里直接抛出异常
// validate openId
if (noOpenForUser(request)){
// 自定义异常
throw new BizException(BizErrorEnum.NOOPENID);
}
// validate phone 这里验证使用某些注解标识的 特殊方法,本项目中校验用户是否
// 授权过手机号
if (validatePhoneAndAddUser(request,handler)){
// 自定义异常
throw new BizException(BizErrorEnum.NOAUTHOPHONE);
}
// 验证通过放行
return true;
}
/**
* 用户手机号
* @param request
* @param handler
* @return
*/
private boolean validatePhoneAndAddUser(HttpServletRequest request,Object handler) {
// 访问的方法是否被自定义(NeedUserPhoneAnnotation )注解 修饰
NeedUserPhoneAnnotation annotation = verifyAnnotation(handler);
if(null == annotation){
return false;
}
// get user phone 如果修饰说明需要特殊校验,本文的实现方式为:
// 用户在授权手机号后将此用户的唯一key 和手机号放入redis 的map 集合中
// 如果用户授权了手机号则直接放行,否则不予通过
String authorization = request.getHeader(UserConstant.mAuthorization);
if (redisUtil.hExists(UserConstant.wxSqPhone, authorization)){
return false;
}
return true;
}
/**
* 注解获取-- 验证详情页等需要授权手机号访问
* @param handler
* @return
*/
private NeedUserPhoneAnnotation verifyAnnotation(Object handler) {
NeedUserPhoneAnnotation permit= null;
if (handler instanceof HandlerMethod){
permit = ((HandlerMethod) handler).getMethod().getAnnotation(NeedUserPhoneAnnotation.class);
// if(permit == null){
// permit = ((HandlerMethod) handler).getBeanType().getAnnotation(NeedUserPhoneAnnotation.class);
// }
}
return permit;
}
/**
* 用户是否已经进行登录 -- 是否用用openid
* 配合业务登录使用,本项目实现方式为,用户完成登录后,返回前端用户登录token
* 前端在访问后端接口时,将此token 令牌放入到请求头的header 进行访问
* @param request
* @return
*/
private boolean noOpenForUser(HttpServletRequest request) {
String authorization = request.getHeader(UserConstant.mAuthorization);
if (StringUtils.isEmpty(authorization)){
return true;
}
if (!redisUtil.hExists(UserConstant.wxLogin, authorization)){
return true;
}
return false;
}
}
1.2 新建类实现WebMvcConfigurer 将拦截器注入到spring 中
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Value("${token.skip-urls-pattern:abcdefg}")
private String skipUrlsPattern;
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> excludePaths = StringUtils.isEmpty(this.skipUrlsPattern) ?
Collections.emptyList() : Splitter.on(",").splitToList(this.skipUrlsPattern);
registry.addInterceptor(authorizationInterceptor())
.excludePathPatterns(excludePaths);
}
// 注入的条件开启token 校验
@Bean
@ConditionalOnProperty(value = "token.enable", havingValue = "true", matchIfMissing = true)
public AuthorizationInterceptor authorizationInterceptor() {
return new AuthorizationInterceptor();
}
}
2 过程:
2.1 HandlerInterceptor:
default boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler)throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler,@Nullable ModelAndView modelAndView) throws Exception {
}
default void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler,@Nullable Exception ex) throws Exception {
}
拦截器基于AOP 实现 HandlerInterceptor 中存在请求进入方法前和进入方法后的方法,只要实现改类并且覆盖掉对应的方法即可;
2.2 AuthorizationInterceptor 实现 HandlerInterceptor 并且覆盖对应的方法:
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
// do something
}
}
2.3 将我们定义的拦截器注入到spring 中:
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthorizationInterceptor())
}
}