小编典典

针对不同端点的多个用户详细信息服务

spring-boot

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

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

我还将设置一个DaoAuthenticationProvider以使用我的用户详细信息服务,并使用该服务来配置全局安全性。

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

如何将两个不同的用户详细信息服务用于不同的端点?


阅读 331

收藏
2020-05-30

共1个答案

小编典典

您可以做的一件事是有两个WebSecurityConfigurerAdapters:

@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()用于将springSecurityFilterChains 定位到特定端点。

2020-05-30