?java服务常用技术-拦截器-用户登录、token、权限校验
springboot拦截器主要目标:
- 拦截请求,验证请求的用户对访问的资源是否有访问权限;
- 需要排除一些不在权限控制范围内的url,如swagger的接口文档列表;
- 需要排除的url,在配置文件中进行配置;
- 双拦截器
一些不需要拦截的,通过addInterceptor.excludePathPatterns排除掉,排除路径通过配置项注入ignorePath
在配置文件application.properties里添加如下配置项
ignorePath=/swagger/**
需要拦截的正常拦截
这里我们通过双拦截器分别实现用户两个功能
- 校验用户token合法性;
- 判断用户对访问资源是否有权限;
这里是启动类,这里加入两个拦截器:WebMvcAuthorizationConfig.java
/**
* @author ikong
* @create 2019-06-01 15:22
*/
@ConditionalOnBean(EmployeeValidateInterceptor.class)
@Configuration
public class WebMvcAuthorizationConfig extends WebMvcConfigurerAdapter {
@Value("${ignore-path}")
private String ignorePath = "";
@Override
public void addInterceptors(InterceptorRegistry registry) {
String pathPattern = "/**";
String pathError = "/error";
InterceptorRegistration addInterceptor = registry.addInterceptor(createTokenInterceptorConfig());
addInterceptor.addPathPatterns("/**");
addInterceptor.excludePathPatterns(new String[]{"/error"});
if (!StringUtils.isEmpty(ignorePath)) {
String[] paths = ignorePath.split(";");
for (int i = 0; i < paths.length; i++) {
addInterceptor.excludePathPatterns(new String[]{paths[i]});
}
}
System.out.println("初始化注入过滤路径:" + JSONObject.toJSONString(ignorePath));
InterceptorRegistration employeeInterceptor =registry.addInterceptor(createEmployeeInterceptorConfig());
employeeInterceptor.addPathPatterns(pathPattern);
employeeInterceptor.excludePathPatterns(pathError);
super.addInterceptors(registry);
}
@Bean
public TokenValidateInterceptor createTokenInterceptorConfig() {
return new TokenValidateInterceptor();
}
@Bean
public EmployeeValidateInterceptor createEmployeeInterceptorConfig() {
return new EmployeeValidateInterceptor();
}
}
验证token合法性:TokenValidateInterceptor.java
/**
* @ClassName TokenValidateInterceptor
* @Description: 拦截器
* @Author ikong
* @Date 2019/8/24
* @Version V1.0
**/
@Component
public class TokenValidateInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(TokenValidateInterceptor.class);
@AutoWired
private TokenService tokenService;
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception {
String token = getToken(HttpServletRequest req)
bool valid = tokenService.validate(token);//验证token是否合法,token不存在或者不合法均返回false;
return valid
}
private String getToken(HttpServletRequest req){
//从请求中获取到当前的token
}
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object o, Exception e) throws Exception {
}
}
验证登录的员工对当前应用是否有访问权限:EmployeeValidateInterceptor.java
/**
* @ClassName EmployeeValidateInterceptor
* @Description: 拦截器
* @Author ikong
* @Date 2019/8/21
* @Version V1.0
**/
@Component
public class EmployeeValidateInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(EmployeeValidateInterceptor.class);
@AutoWired
private EmployeeService employeeService;
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception {
String token = getToken(HttpServletRequest req);
String uri = req.getRequestURI();
bool valid = employeeService.hasRight(token,uri);//验证token是否合法,token不存在或者不合法均返回false;
return valid
}
private String getToken(HttpServletRequest req){
//从请求中获取到当前的token
}
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object o, Exception e) throws Exception {
}
}
回顾一下 HandlerInterceptor 几个实现方法的用途描述
1、preHandle
调用时间:Controller方法处理之前
执行顺序:链式Intercepter情况下,Intercepter按照声明的顺序一个接一个执行
若返回false,则中断执行,注意:不会进入afterCompletion
2、postHandle
调用前提:preHandle返回true
调用时间:Controller方法处理完之后,DispatcherServlet进行视图的渲染之前,也就是说在这个方法中你可以对ModelAndView进行操作
执行顺序:链式Intercepter情况下,Intercepter按照声明的顺序倒着执行。
备注:postHandle虽然post打头,但post、get方法都能处理
3、afterCompletion
调用前提:preHandle返回true
调用时间:DispatcherServlet进行视图的渲染之后
多用于清理资源,比如 自定义的localthread,清理当前web请求线程下的线程变量,以防止内存溢出
?
|