Spring Security 如何使用spring的新配置API配置带有@Secured annotation的RoleHierarchy?

50pmv0ei  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(198)

以前,这种设置足以使用RoleHierarchy@Secured注解。但现在不推荐使用。

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
@RequiredArgsConstructor
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    private final RoleHierarchy roleHierarchy;
    private final RoleVoter roleVoter;
    private final AuthenticatedVoter authenticatedVoter;
    private final Jsr250Voter jsr250Voter;

    @Override
    protected AccessDecisionManager accessDecisionManager() {
        var expressionHandler = (DefaultMethodSecurityExpressionHandler) getExpressionHandler();
        expressionHandler.setRoleHierarchy(roleHierarchy);

        var expressionAdvice = new ExpressionBasedPreInvocationAdvice();
        expressionAdvice.setExpressionHandler(expressionHandler);

        return new AffirmativeBased(List.of(
                roleVoter,
                new PreInvocationAuthorizationAdviceVoter(expressionAdvice),
                authenticatedVoter,
                jsr250Voter
        ));
    }
}

字符串
The documentation说这是新的方式。但是在这种配置下。RoleHierarchy不使用@Secured注解。

@Configuration
@EnableMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Bean
    static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
        DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
        handler.setRoleHierarchy(roleHierarchy);
        return handler;
    }
}


我错过了什么?

xghobddn

xghobddn1#

您可以直接定义顾问bean,如下所示

@Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    static AuthorizationManagerBeforeMethodInterceptor securedAuthorizationAdvisor() {
        SecuredAuthorizationManager manager = new SecuredAuthorizationManager();
        AuthoritiesAuthorizationManager authoritiesAuthorizationManager = new AuthoritiesAuthorizationManager();
        authoritiesAuthorizationManager.setRoleHierarchy(authorities -> null);//set your RoleHierarchy
        manager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager);
        return AuthorizationManagerBeforeMethodInterceptor.secured(manager);
    }

字符串
官方文档说明:
RoleHierarchy bean配置尚未移植到@EnableMethodSecurity。因此,此示例使用的是RodeDecisionVoter。如果您需要RoleHierarchy支持方法安全性,请继续使用@EnableGlobalMethodSecurity,直到gh-12783完成。目前,我看到PR-14260已合并到6.3.0-M1里程碑中。

相关问题