场景
在博主目前正在开发的项目中,就采用了Sa-Token作为权限框架支持,并且同时使用了注解和路由的拦截器模式,此部分的配置如下:
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> notMatches = CollectionUtil.newArrayList();
registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");
registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
SaRouter.match("/**").notMatch(notMatches).check(r -> StpUtil.checkLogin());
})).addPathPatterns("/**");
}
在上述的配置中代表除开notMatches中其他所有的路径都会进行StpUtil.checkLogin()方法来验证是否登录,如果没有登录则会未登录的异常。
但是有的时候又一个个去配置路径太麻烦了,特别是许多接口模块的情况下,于是采用允许匿名访问的注解模式就为一个不错的方法。
引入
首先我们需要新建一个注解,允许它在类及方法上使用:
/**
* 匿名接口,提供SaToken中缺失的匿名注解访问
*
* @author Licoy
* */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD,})
public @interface AnonymousApi {
}
后面我们再到Sa-Token的拦截器配置中判断执行的方法是否含有此注解,如果有则使用SaRouter.stop()停止匹配,跳出函数。
现在我们修改一下上一小节中的代码:
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> notMatches = CollectionUtil.newArrayList();
registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");
registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
if (handler instanceof HandlerMethod) {
Method method = ((HandlerMethod) handler).getMethod();
if (method.getAnnotation(AnonymousApi.class) != null || method.getDeclaringClass().getAnnotation(AnonymousApi.class) != null) {
SaRouter.stop();
}
}
SaRouter.match("/**").notMatch(notMatches).check(r -> StpUtil.checkLogin());
})).addPathPatterns("/**");
}
至此,我们就可以愉快的使用@AnonymousApi来允许接口的匿名访问了。
后记
在权限框架中,我们会有很多的特殊路径权限,不得不说Sa-Token为我们提供了一种方便快捷的方式,我看了文档几分钟就完全配置出来了,要是按照以前使用Shiro或者Spring Security,至少都要以天为单位(又或者是因为现在的经验甚比以前了)