Spring Security中hasAnyAuthority是否支持通配符匹配?
默认情况下,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
相关产品推荐
相关产品推荐

