You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何在@PreAuthorize的hasAuthority中使用字符串包含或正则匹配

在Spring Boot 2.7.6中用@PreAuthorize实现权限的模糊/正则匹配

方法一:SpEL结合contains子串匹配

Spring Security的SpEL支持直接操作当前认证用户的权限集合,你可以通过内置的authentication对象获取所有权限,再遍历判断是否存在包含指定子串的权限。

比如匹配所有含MYAPI_ORDER_的权限,写法如下:

@PreAuthorize("authentication.authorities.anyMatch(auth -> auth.authority.contains('MYAPI_ORDER_'))")
public void yourProtectedMethod() {
    // 业务逻辑代码
}

这里authentication.authorities是当前用户的权限集合,anyMatch用于遍历集合,只要有一个权限满足contains的子串匹配条件,就会通过校验。

方法二:SpEL结合正则表达式匹配

如果需要更灵活的规则(比如匹配特定前缀/后缀或复杂格式),可以用matches方法搭配正则表达式:

@PreAuthorize("authentication.authorities.anyMatch(auth -> auth.authority.matches('^MYAPI_ORDER_.*$'))")
public void yourProtectedMethod() {
    // 业务逻辑代码
}

示例中的正则^MYAPI_ORDER_.*$表示匹配以MYAPI_ORDER_开头的所有权限字符串,你可以根据需求调整正则规则。

方法三:自定义Security表达式(复用场景推荐)

如果多个接口都需要用到这类匹配逻辑,重复写SpEL会冗余,建议封装成自定义表达式方法:

  1. 先创建自定义表达式组件:
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

@Component("customSecurityExpressions")
public class CustomSecurityExpressions {

    // 子串匹配方法
    public boolean hasAuthorityContaining(Authentication auth, String substring) {
        return auth.getAuthorities().stream()
                .anyMatch(grantedAuth -> grantedAuth.getAuthority().contains(substring));
    }

    // 正则匹配方法
    public boolean hasAuthorityMatchingRegex(Authentication auth, String regex) {
        return auth.getAuthorities().stream()
                .anyMatch(grantedAuth -> grantedAuth.getAuthority().matches(regex));
    }
}
  1. 在接口上调用自定义方法:
@PreAuthorize("@customSecurityExpressions.hasAuthorityContaining(authentication, 'MYAPI_ORDER_')")
public void yourProtectedMethod() {
    // 业务逻辑代码
}

// 正则匹配用法
@PreAuthorize("@customSecurityExpressions.hasAuthorityMatchingRegex(authentication, '^MYAPI_ORDER_.*$')")
public void anotherProtectedMethod() {
    // 业务逻辑代码
}

这种方式把匹配逻辑抽离出来,方便多处复用,也更易维护。


内容的提问来源于stack exchange,提问作者pixel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:47:39