Spring Security6 教程

AuthorityAuthorizationManager 授权管理器

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 和灵活的配置,它能轻松实现基于角色或权限的细粒度访问控制。

 

说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号