简介
一般在web项目中,定义拦截器就是为了对用户进行鉴权,常用的方式就是拦截所有请求,从session或token获取用户的登录状态信息。但是这种配置式的拦截器配置不够灵活,所以我们可以自定义注解进行拦截,在需要被拦截的接口上直接添加注解,方便快捷
一、创建注解类
/**
* @Created with IDEA
* @author: bobinghua
* @see:
* @description:
* @Date: 2019/5/10
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})// 让该注解可以注解在方法和类上
public @interface Security {
}
二、创建拦截器类
/**
* @Created with IDEA
* @author: bobinghua
* @see:
* @description:
* @Date: 2019/5/10
*/
@Component
public class SecurityInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/**
* handler保存了本次请求的controller也就是接口方法的一些信息,如类,方法,参数等
* 如果是一次静态资源的请求则该handler不应该是HandlerMethod的实现类
* 判断是否是一个正常的接口,如果是则进行鉴权操作,不是则直接放行
*/
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;// 把handler强转为HandlerMethod
// 从handlerMethod中获取本次请求的接口方法对象然后判断该方法上是否标有我们自定义的注解@Security
Security security = handlerMethod.getMethod().getAnnotation(Security.class);
if (null != security) {
// 对用户进行鉴权
if (hasPermission())
return true;
return false;
}
}
return true;
}
// 用户鉴权具体方法
private boolean hasPermission() {
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
三、配置拦截器
创建spring自定义配置类并实现WebMvcConfigurer接口实现addinterceptors方法
/**
* @Created with IDEA
* @author: bobinghua
* @see:
* @description:
* @Date: 2019/5/10
*/
@Configuration
public class InterceporConfig implements WebMvcConfigurer {
@Autowired
private SecurityInterceptor securityInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(securityInterceptor)// 注册拦截器
.addPathPatterns("/**");// 拦截所有请求
}
}
到这里我们只需要在需要对用户鉴权的接口方法上加上@Security注解就可以对该接口进行拦截。如果需要实现更详细的接口权限控制的话还可以在注解传入该接口需要的权限等级列表,统一在拦截器中进行鉴权