当内置管理器无法满足需求时,可实现 AuthorizationManager<T> 接口自定义授权管理器。这样我们就可以根据业务需要,实现更复杂到授权管理。例如:
http.authorizeHttpRequests(authorize -> authorize
// 需要具有 admin 角色权限才能访问 /sys 路径的请求
.requestMatchers("/sys/**").access(new AuthorizationManager<RequestAuthorizationContext>() {
@Override
public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
boolean isAllowed = false;
// 判断是否拥有 my-header 请求头,并且值为 hxstrive.com
String myHeader = object.getRequest().getHeader("my-header");
if(Objects.equals(myHeader, "hxstrive.com")) {
isAllowed = true; // 允许访问
}
return new AuthorizationDecision(isAllowed);
}
})
.anyRequest().authenticated() // 其他请求需认证
)重启应用,访问 http://localhost:8080/sys/add 地址验证,如下图:
(1)访问成功

(2)访问失败
