spring - 不同端点的多个用户详细信息服务

标签 spring spring-boot spring-security basic-authentication

我正在使用 Spring 构建 REST API,并且目前正在使用自定义用户详细信息服务和以下配置代码对我的所有请求进行身份验证:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}

我也在设置DaoAuthenticationProvider使用我的用户详细信息服务并使用它来配置全局安全性。

现在,我想提供一个端点(虽然仍然使用 HTTP 基本身份验证进行保护)使用不同的用户详细信息服务来检查是否允许用户访问给定资源。

如何为不同的端点使用两种不同的用户详细信息服务?

最佳答案

您可以做的一件事就是拥有两个 WebSecurityConfigurerAdapter s:

@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
class FirstEndpointConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) {
        http
            .requestMatchers()
                .antMatchers("/specialendpoint")
                .and()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.userDetailsService(/* first of your userDetailsServices */);
    }
}


@Configuration
class SecondEndpointConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) {
        http // all other requests handled here
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.userDetailsService(/* second of your userDetailsServices */);
    }
}
requestMatchers()存在用于定位 springSecurityFilterChain s 到特定端点。
编辑 :Mahmoud Odeh 提出了一个很好的观点,如果用户群相同,那么您可能不需要多个 UserDetailsService实例。相反,您可以使用一项更改,通过用户帐户的权限来隔离您的特殊端点:
http
    .authorizeRequests()
        .antMatchers("/specialendpoint").hasAuthority("SPECIAL")
        .anyRequest().authenticated()
        .and()
    .httpBasic();
那么,你的单例UserDetailsService会查找所有用户。它将包括 SPECIAL GrantedAuthorityUserDetails对于有权访问 /specialendpoint 的用户的实例.

关于spring - 不同端点的多个用户详细信息服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49450556/

相关文章:

hibernate - 重复结果休息服务 Spring boot

java - Spring:如何仅在Web应用程序中调用方法?

java - Spring Web MVC Java 配置-默认 Servlet 名称

java - Spring Security部署错误

java - Spring Cloud Config Server - 连接 github 的用户名和密码

spring - 自定义身份验证提供程序的工作原理

java - 如何在 Spring-Boot 中使用 SSL 证书并为 Android 客户端生成公钥

java - Spring 安全: Can other beans access the global AuthenticationManagerBuilder?

java - 定位实例化的原型(prototype) bean

java - Log4j2 - 除 Spring 之外的调试级别日志记录