feat: SaInterceptor 新增 beforeAuth 认证前置函数

This commit is contained in:
click33 2025-05-15 22:32:54 +08:00
parent a5ea1a3a4d
commit edbd63f81b
2 changed files with 45 additions and 7 deletions

View File

@ -225,7 +225,7 @@ public SaResult getList() {
### 7、关闭注解校验
`SaInterceptor` 只要注册到项目中,默认就会打开注解校验,如果要关闭此能力,需要:
`SaInterceptor` 只要注册到项目中,默认就会打开注解校验,如果要关闭此能力,需要指定 `isAnnotation` 为 false
``` java
@Override
@ -238,6 +238,26 @@ public void addInterceptors(InterceptorRegistry registry) {
}
```
你也可以使用 `setBeforeAuth` 注册认证前置函数:
``` java
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SaInterceptor(handle -> {
System.out.println(1);
})
.setBeforeAuth(handle -> {
System.out.println(2);
})
).addPathPatterns("/**");
}
```
如上代码,先执行 2再执行注解鉴权再执行 1如果 beforeAuth 里包含 `SaRouter.stop()` 将跳过后续的注解鉴权和 auth 认证环节。
---
<a class="case-btn" href="https://gitee.com/dromara/sa-token/blob/master/sa-token-demo/sa-token-demo-case/src/main/java/com/pj/satoken/SaTokenConfigure.java"

View File

@ -39,6 +39,12 @@ public class SaInterceptor implements HandlerInterceptor {
*/
public boolean isAnnotation = true;
/**
* 认证前置函数在注解鉴权之前执行
* <p> 参数路由处理函数指针
*/
public SaParamFunction<Object> beforeAuth = handler -> {};
/**
* 认证函数每次请求执行
* <p> 参数路由处理函数指针
@ -69,6 +75,16 @@ public class SaInterceptor implements HandlerInterceptor {
return this;
}
/**
* 写入 [ 认证前置函数 ]: 在注解鉴权之前执行
* @param beforeAuth /
* @return 对象自身
*/
public SaInterceptor setBeforeAuth(SaParamFunction<Object> beforeAuth) {
this.beforeAuth = beforeAuth;
return this;
}
/**
* 写入 [ 认证函数 ]: 每次请求执行
* @param auth /
@ -91,6 +107,8 @@ public class SaInterceptor implements HandlerInterceptor {
throws Exception {
try {
// 前置函数在注解鉴权之前执行
beforeAuth.run(handler);
// 这里必须确保 handler HandlerMethod 类型时才能进行注解鉴权
if(isAnnotation && handler instanceof HandlerMethod) {