您现在的位置是:亿华云 > 域名

聊聊 Spring Security 的新接口 AuthorizationManager

亿华云2025-10-09 01:20:02【域名】5人已围观

简介Spring Security 5.5 增加了一个新的授权管理器接口AuthorizationManager,它让动态权限的控制接口化了,更加方便我们使用了,今天就来分享以下最新

Spring Security 5.5 增加了一个新的聊聊授权管理器接口AuthorizationManager,它让动态权限的接口控制接口化了,更加方便我们使用了,聊聊今天就来分享以下最新的接口研究成果,一键四连走起。聊聊

抢一个玩玩吧,接口别忘了分享给别的聊聊同学们。

AuthorizationManager

它用来检查当前认证信息Authentication是接口否可以访问特定对象T。AuthorizationManager将访问决策抽象更加泛化。聊聊

@FunctionalInterface

public interface AuthorizationManager{

default void verify(Supplier authentication,接口 T object) {

AuthorizationDecision decision = check(authentication, object);

// 授权决策没有经过允许就403

if (decision != null && !decision.isGranted()) {

throw new AccessDeniedException("Access Denied");

}

// todo 没有null 的情况

}

// 钩子方法。

@Nullable

AuthorizationDecision check(Supplier authentication,聊聊 T object);

}

我们只需要实现钩子方法check就可以了,它将当前提供的接口认证信息authentication和泛化对象T进行权限检查,源码库并返回AuthorizationDecision,聊聊AuthorizationDecision.isGranted将决定是接口否能够访问当前资源。AuthorizationManager提供了两种使用方式。聊聊

基于配置

为了使用AuthorizationManager,引入了相关配置是AuthorizeHttpRequestsConfigurer,这个配置类非常类似于第九章中的基于表达式的访问控制。

基于AuthorizationManager的访问控制.png

在Spring Security 5.5中,我们就可以这样去实现了:

// 注意和 httpSecurity.authorizeRequests的区别

httpSecurity.authorizeHttpRequests()

.anyRequest()

.access((authenticationSupplier, requestAuthorizationContext) -> {

// 当前用户的权限信息 比如角色

Collection authorities = authenticationSupplier.get().getAuthorities();

// 当前请求上下文

// 我们可以获取携带的参数

Mapvariables = requestAuthorizationContext.getVariables();

// 我们可以获取原始request对象

HttpServletRequest request = requestAuthorizationContext.getRequest();

//todo 根据这些信息 和业务写逻辑即可 最终决定是否授权 isGranted

boolean isGranted = true;

return new AuthorizationDecision(isGranted);

});

这样门槛是不是香港云服务器低多了呢?同样地,它也可以作用于注解。

基于注解

AuthorizationManager还提供了基于注解的使用方式。但是在了解这种方式之前我们先来看看它的实现类关系:

AuthorizationManager的实现

胖哥发现这一点也是从AuthorizationManager的实现中倒推出来的,最终发现了@EnableMethodSecurity这个注解,它的用法和@EnableGlobalMethodSecurity类似,对同样的三种注解(参见EnableGlobalMethodSecurity)进行了支持。用法也几乎一样,开启注解即可使用:

@EnableMethodSecurity(

securedEnabled = true,

jsr250Enabled = true)

public class MethodSecurityConfig {

}

例子就不在这里重复了。站群服务器

很赞哦!(958)