java - Spring Boot/Spring Security 根据路径在多个认证提供者之间进行选择

标签 java spring spring-boot spring-security

我已将我的应用程序配置为:

我有两个身份验证提供程序(provider1 和 provider2),我想将它们用于不同的端点:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/api/v1").authenticated();
    http.authorizeRequests().antMatchers("/api/v2").authenticated();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(provider1);
    auth.authenticationProvider(provider2);
}

现在如果我调用 /api/v2 会发生什么provider1被调用,如果不引发异常或返回 false 则只有 provider2被调用。
// In org.springframework.security.authentication.ProviderManager

for (AuthenticationProvider provider : getProviders()) {
        try {
            result = provider.authenticate(authentication);

            if (result != null) {
                copyDetails(authentication, result);
                break;
            }
        }
        ...
        ...
}

我怎样才能做到只有 provider2当我点击 /api/v2 时被调用?

像这样的东西:
http.authorizeRequests().antMatchers("/api/v2")
    .authenticated().authenticationProvider(provider2);

(我知道 authenticationProvider 上有 HttpSecurity ,但是,这与调用 AuthenticationManagerBuilder#authenticationProvider 完全相同)

最佳答案

您可以向 Spring Security 过滤器链添加一个自定义过滤器,该过滤器尝试使用自定义 Authentication 授权请求。执行。当您调用 AuthenticationManager.authenticate() ,您可以传入自定义身份验证的实例。然后确保您更新了您的自定义提供程序的 supports(Class authentication) 方法以仅接受您的自定义身份验证类。

然后,您可以使用 antmatchers 将自定义过滤器应用于特定端点的安全过滤器链。

关于java - Spring Boot/Spring Security 根据路径在多个认证提供者之间进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078836/

相关文章:

java - 使用 spring-DM 扩展器进行 OSGi 日志记录不进行日志记录

java - 如何在 JTextArea 中设置列​​以显示文本

java - Spring Data Rest 2.0.0.RELEASE 打破了以前使用 RC1 的代码

java - 如何在Python中表示Unicode编码的字符串?

java - 是否可以从 spring 应用程序属性中获取自定义对象?

java - 使用mockito和spring mock的authowired bean的Mock方法

java - 如何在 spring AOP 类中使用 HystrixCommand

spring-boot - Date 的默认序列化格式是否随着最近的 Spring Boot 版本/Jackson 版本而改变?

java - 将 Grizzly2.2.X 与 Jersey 和 Spring 集成

java - 如何使用 Jersey 将对象传递到 REST Web 资源