有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

oauth2和其他身份验证提供程序的java WebSecurity配置程序

我的应用程序上有2种类型的用户。一种类型可以使用LDAP AuthenticationProvider,另一种类型可以使用Salesforce Oauth2。他们都需要访问我的API

我的Web安全配置适配器中有以下内容:

        // Config for LDAP
    httpSecurity
        .csrf().disable().headers().frameOptions().deny()
        .and()      
        .authorizeRequests().antMatchers("/admin/login").permitAll().       
        antMatchers("/admin/**").authenticated()
        .and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

        // Config for Salesforce Oauth2
    httpSecurity.csrf().disable().headers().frameOptions().deny().and().
        authorizeRequests().antMatchers("/client/**").authenticated()
         .and()
         .oauth2Login()
         .userInfoEndpoint()
         .userService(myOAuth2UserService);

我想我可以在同一个WebConf中使用这两种配置,但它并没有像预期的那样工作,因为当我调用/client时,我遇到了一个错误401。但是,如果我删除了第一个LDAP配置,那么效果会很好

有没有一种方法可以同时使用身份验证解决方案实现配置


共 (1) 个答案

  1. # 1 楼答案

    您可以使用提供程序为每个实现注册,然后向Spring AuthenticationManager注册此提供程序

    @Component
    public class CustomAuthenticationProvider implements AuthenticationProvider {
        @Override
        public Authentication authenticate(Authentication auth) 
          throws AuthenticationException {
            //Implementaton for Authentication
        }
    
        @Override
        public boolean supports(Class<?> auth) {
            return auth.equals(UsernamePasswordAuthenticationToken.class);
        }
    }
    

    现在,在WebSecurity配置适配器中,您可以注册多个身份验证提供程序

    @EnableWebSecurity
    public class MultipleAuthProvidersSecurityConfig 
      extends WebSecurityConfigurerAdapter {
        @Autowired
        CustomAuthenticationProvider customAuthProvider;
    
        @Override
        public void configure(AuthenticationManagerBuilder auth) 
          throws Exception {
    
            auth.authenticationProvider(customAuthProvider);
            auth.inMemoryAuthentication()
                .withUser("memuser")
                .password(encoder().encode("pass"))
                .roles("USER");
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers("/api/**")
                .authenticated();
        }
        
         
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
    

    在本例中,有一个CustomAuthenticationProvider,另一个是InMemoryAuthentication提供程序。您始终可以编写自己的提供者的实现

    资料来源:https://www.baeldung.com/spring-security-multiple-auth-providers