生成中接口的請求必須加token進(jìn)行權(quán)限校驗(yàn),比如校驗(yàn)是否登錄獲取的token焕窝,校驗(yàn)該用戶是否具體該接口訪問權(quán)限等等袜啃。
這里以判斷用戶是否登錄做例子進(jìn)行講解幸缕。
配置SpringContextUtil
項(xiàng)目中如果靜態(tài)類根據(jù)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 該類的實(shí)例
*/
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) {
//狀態(tài)設(shè)置為未授權(quán)
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查到休涤,則具備權(quán)限笛辟。
增加攔截器配置CheckLoginConfig
@Configuration
public class CheckLoginConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//校驗(yàn)是否登錄攔截器
registry.addInterceptor(new CheckLoginInterceptor())
//消息相關(guān)
.addPathPatterns("/news/*");
super.addInterceptors(registry);
}
}
這里面以url的通配符來作為攔截器的格式,這里只加入/news/*
相關(guān)的捷凄,其余的比如登錄接口是不需要校驗(yàn)的围来。
測試未登錄
直接輸入接口,進(jìn)行訪問钦铁,會提示如下錯誤:
請求header增加Authorization