auth-manager中的条件授权提供程序

时间:2018-02-27 16:01:58

标签: java spring spring-security

我通过xml进行安全配置。我已经添加了额外的提供商。所以它看起来像这样:

<sec:authentication-manager alias="authenticationManager">
    <sec:authentication-provider ref="first" />
    <sec:authentication-provider ref="second">
    </sec:authentication-provider>
</sec:authentication-manager>

我想根据app.properties文件中的条目使用两个提供程序或只使用一个。它甚至可能吗?

1 个答案:

答案 0 :(得分:2)

可能最简单的方法是让每个AuthenticationProvider回答自己。您可以实施supports方法,也可以选择从null返回authenticate,表示此AuthenticationProvider弃权。

覆盖supports

public class FirstAuthenticationProvider implements AuthenticationProvider {

    @Value("${myapp.security.usefirst}") boolean useFirst;

    @Override
    public boolean supports(Class<?> authentication) {
        return useFirst && anyOtherTestingNecessary;
    }
}

AuthenticationProvider弃权

public class SecondAuthenticationProvider implements AuthenticationProvider {

    @Value("${myapp.security.usefirst}") boolean useFirst;

    @Override
    public Authentication authenticate(Authentication authentication) {
        if ( useFirst ) {
            return null; // abstain
        }

        // ... rest of authentication strategy
    }

}

如果您使用的是Spring 4或更高版本,则可以使用@Conditional注释根据您的属性有条件地连接每个提供商,但根据您的问题,我会放弃该示例。

当然,您可以按照评论中的建议创建一个包装器AuthenticationProvider,但这可能会导致一些胃灼热,具体取决于您的布线策略。此外,它正在重复ProviderManager已经打算做的一些工作。