Warm tip: This article is reproduced from serverfault.com, please click

spring-ActiveDirectoryLdapAuthenticationProvider和使用userDetailsS​​ervice的身份验证

(spring - ActiveDirectoryLdapAuthenticationProvider and authentication using userDetailsService)

发布于 2020-12-01 00:30:39

我的应用程序中有两个不同的用户。Ldap用户和api用户。Ldap用户具有访问端点的权限,而api用户则具有不同的端点的权限。我已经使用UserDetailsS​​ervice实现了api用户身份验证,并在我的application.yaml文件中包含了详细信息。我现在面临的问题是,我的api用户也正在访问仅Ldap用户应访问的终结点。我该如何预防。请在下面找到我的代码段

public class ServiceSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("ldapProvider")
    private AuthenticationProvider authenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

// security for apiuser
              http
                .authorizeRequests()
                .antMatchers(“/abcd/**).hasRole(“admin”)
                .and()
                .httpBasic().and().userDetailsService(userDetailsService());
      

// security for ldap users
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(“/ghhgh” + "/**").fullyAuthenticated()
                .antMatchers("/login*").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().and()
                .authenticationProvider(authenticationProvider)
                .exceptionHandling();
    }

    public UserDetailsService userDetailsService() {

        UserDetails user = User.withUsername(“api”)
                .password(passwordEncoder().encode(“test”))
                .roles(“admin”)
              return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
Questioner
SJB
Viewed
11
Amir Schnell 2020-12-03 18:38:04

在 Spring 安全性中,确实有可能注册多个身份验证机制。

但是你不能将特定的身份验证提供程序注册到特定的路由。
Spring 安全性文档说:

ProviderManager是的最常用的实现AuthenticationManagerProviderManager代表ListAuthenticationProviders每个人AuthenticationProvider都有机会表明身份验证应该成功,失败,或者表明它无法做出决定并允许下游AuthenticationProvider做出决定。

因此,在每个请求中,AuthenticationProvider都将一个接一个地检查注册的s,直到一个成功或全部失败。

要解决你的问题,你需要定义多个自定义权限,并为你分配用户。
然后,你可以使用这些权限保护端点。

例如,你赋予每个ldap用户权限LDAP_USER和每个api用户权限API_USER然后,你可以相应地配置安全性:

注册所有AuthenticationProviders:


@Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(ldapProvider);
        auth.userDetailsService(userDetailsService());
    }

并配置端点:


@Override
protected void configure(HttpSecurity http) throws Exception {


    http
      (...)
      .authorizeRequests()

// security for apiuser
      .antMatchers(“/abcd/**).hasRole(“API_USER”)

// security for ldap users
      .antMatchers(“/ghhgh” + "/**").hasRole("LDAP_USER")
      (...)
    }