0
点赞
收藏
分享

微信扫一扫

内有红包封面|Spring Security的新接口AuthorizationManager


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

文末有胖哥设计的程序员专属红包封面

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

AuthorizationManager

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

@FunctionalInterface
public interface AuthorizationManager<T> {

default void verify(Supplier<Authentication> 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> authentication, T object);

}

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

基于配置

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

内有红包封面|Spring Security的新接口AuthorizationManager_接口

基于AuthorizationManager的访问控制.png

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

// 注意和 httpSecurity.authorizeRequests的区别
httpSecurity.authorizeHttpRequests()
.anyRequest()
.access((authenticationSupplier, requestAuthorizationContext) -> {
// 当前用户的权限信息 比如角色
Collection<? extends GrantedAuthority> authorities = authenticationSupplier.get().getAuthorities();
// 当前请求上下文
// 我们可以获取携带的参数
Map<String, String> variables = requestAuthorizationContext.getVariables();
// 我们可以获取原始request对象
HttpServletRequest request = requestAuthorizationContext.getRequest();
//todo 根据这些信息 和业务写逻辑即可 最终决定是否授权 isGranted
boolean isGranted = true;
return new AuthorizationDecision(isGranted);
});

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

基于注解

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

内有红包封面|Spring Security的新接口AuthorizationManager_设计模式_02

AuthorizationManager的实现

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

@EnableMethodSecurity(
securedEnabled = true,
jsr250Enabled = true)
public class MethodSecurityConfig {

}

例子就不在这里重复了。

这个是​Spring Security 5.6​版本的新玩法,不要搞错了,它默认支持​​prePostEnabled​​。



举报

相关推荐

0 条评论