AuthorityAuthorizationManager 类基于用户权限(如角色、菜单权限)进行授权决策,检查当前用户是否拥有指定的权限,从而决定是否允许访问受保护资源。
AuthorityAuthorizationManager 类的核心功能如下:
权限验证,检查用户是否具备指定的权限(如 ROLE_ADMIN)。
角色前缀处理,支持自动添加或忽略角色前缀(如 ROLE_),通过 withPrefix() 方法配置。
多权限匹配策略,用户只需拥有任意一个权限即可访问。
AuthorityAuthorizationManager 类的核心方法如下:
hasRole(String role) 检查用户是否拥有指定的角色(自动添加默认前缀 ROLE_)。
hasAuthority(String authority) 检查用户是否拥有指定的权限(需完整匹配权限字符串,不自动添加前缀)。
hasAnyRole(String... roles) 检查用户是否拥有任意一个指定的角色(自动添加 ROLE_ 前缀)。
hasAnyRole(String rolePrefix, String[] roles) 检查用户是否拥有任意一个指定角色,并自定义角色前缀(默认前缀为 ROLE_)。
hasAnyAuthority(String... authorities) 检查用户是否拥有任意一个指定的权限(需完整权限字符串,不自动加前缀)。
下面是 AuthorityAuthorizationManager 类到部分源码:
package org.springframework.security.authorization; import java.util.Set; import java.util.function.Supplier; import org.springframework.security.access.hierarchicalroles.NullRoleHierarchy; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; import org.springframework.security.core.Authentication; import org.springframework.util.Assert; public final class AuthorityAuthorizationManager<T> implements AuthorizationManager<T> { private static final String ROLE_PREFIX = "ROLE_"; public static <T> AuthorityAuthorizationManager<T> hasRole(String role) {...} public static <T> AuthorityAuthorizationManager<T> hasAuthority(String authority) {...} public static <T> AuthorityAuthorizationManager<T> hasAnyRole(String... roles) {...} public static <T> AuthorityAuthorizationManager<T> hasAnyRole(String rolePrefix, String[] roles) {...} public static <T> AuthorityAuthorizationManager<T> hasAnyAuthority(String... authorities) {...} //... }
上述源码中,提供了五个静态方法。
创建 AuthorityAuthorizationManager 类的实例,如下:
// 验证用户是否拥有单个权限 AuthorityAuthorizationManager.hasAuthority("read"); // 验证用户是否拥有单个角色(自动添加 ROLE_ 前缀) AuthorityAuthorizationManager.hasRole("admin"); // 验证用户是否拥有任意一个权限 AuthorityAuthorizationManager.hasAnyAuthority("read", "write"); // 验证用户是否拥有任意一个角色 AuthorityAuthorizationManager.hasAnyRole("normal", "admin");
自定义角色前缀,如下:
// 自定义角色前缀(例如使用 "ROLE_" 以外的前缀) AuthorityAuthorizationManager.hasAnyRole("MY_ROLE_", new String[]{ "admin" })
应用于 access() 方法,如下:
http.authorizeHttpRequests(authorize -> authorize // 需要具有 admin 角色权限才能访问 /sys 路径的请求 .requestMatchers("/sys/**").access(AuthorityAuthorizationManager.hasRole("admin")) .anyRequest().authenticated() // 其他请求需认证 )
注意,AuthorityAuthorizationManager 是 Spring Security 中基于权限进行访问控制的核心组件,适用于大多数需要权限验证的场景。通过简洁的 API 和灵活的配置,它能轻松实现基于角色或权限的细粒度访问控制。