生成中接口的请求必须加token进行权限校验,比如校验是否登录获取的token,校验该用户是否具体该接口访问权限等等。
这里以判断用户是否登录做例子进行讲解。
配置SpringContextUtil
项目中如果静态类根据beanId来获取对象,需要提前注入SpringContextUtil。
@SpringBootApplication
public class WebApiStartApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(WebApiStartApplication.class, args);
SpringContextUtil.setApplicationContext(applicationContext);
}
}
启动类中先注入aplicationConotext
SprintContextUtil
public class SpringContextUtil {
/**
* 上下文对象
*/
private static ApplicationContext applicationContext;
public static void setApplicationContext(ApplicationContext context) {
applicationContext = context;
}
/**
*
* @param beanId bean的id
* @return 该类的实例
*/
public static Object getBean(String beanId) {
return applicationContext.getBean(beanId);
}
}
增加拦截器CheckLoginInterceptor
public class CheckLoginInterceptor implements HandlerInterceptor {
/**
* 操作前先判断是否登录,未登录提示未登录
*
* @param request request
* @param response response
* @param handler handler
* @return 处理是否成功
* @throws Exception 异常
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (StringUtil.isNullOrEmpty(request.getHeader("Authorization")) || TokenUtil.getToken(request) == null) {
//状态设置为未授权
response.setStatus(HttpStatus.UNAUTHORIZED.value());
StringUtil.out(response, JsonUtil.toStr(new JsonResult(false, GlobalReturnCode.NO_AUTH)));
return false;
} else {
return true;
}
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
这里是拦截器,在preHandler里面获取header中的Authorization属性,如果该属性不为空,且可以通过redis查到,则具备权限。
增加拦截器配置CheckLoginConfig
@Configuration
public class CheckLoginConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//校验是否登录拦截器
registry.addInterceptor(new CheckLoginInterceptor())
//消息相关
.addPathPatterns("/news/*");
super.addInterceptors(registry);
}
}
这里面以url的通配符来作为拦截器的格式,这里只加入/news/*
相关的,其余的比如登录接口是不需要校验的。
测试未登录
直接输入接口,进行访问,会提示如下错误:
未登录.png
请求header增加Authorization
校验成功.png