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

Spring Security中hasAnyAuthority是否支持通配符匹配?

关于@PreAuthorize中权限通配符的支持问题

默认情况下,hasAnyAuthority()方法是做精确字符串匹配的,不支持SCOPE_qdcac.*这类通配符写法——你当前使用的表达式里,只有当用户拥有完全一致的权限字符串时,才会通过校验。

如果想要实现通配符匹配的需求,可以试试这几种方式:

  • 直接用SpEL结合正则表达式写匹配逻辑:

    @PreAuthorize("hasAuthority('SCOPE_all.adm') or authentication.authorities.anyMatch(auth -> auth.authority matches 'SCOPE_qdcac\\..*')")
    

    这里用正则SCOPE_qdcac\..*匹配所有以SCOPE_qdcac.开头的权限。

  • 自定义工具方法封装通配符匹配逻辑:
    先写一个工具类:

    @Component("securityUtils")
    public class SecurityUtils {
        public boolean hasMatchingAuthority(String pattern) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth == null) return false;
            // 把通配符*转换成正则的.*
            String regexPattern = pattern.replace("*", ".*");
            return auth.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(authority -> authority.matches(regexPattern));
        }
    }
    

    然后在注解里调用:

    @PreAuthorize("@securityUtils.hasMatchingAuthority('SCOPE_all.adm') or @securityUtils.hasMatchingAuthority('SCOPE_qdcac.*')")
    

需要注意:正则里的.是特殊字符,若权限字符串本身包含.,要转义成\.;自定义方法里的转换逻辑可以根据你的通配符规则调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:35:18