programing

서로 다른 인증 공급자와 함께 여러 WebSecurityConfigurerAdapter 사용(API용 기본 인증자 및 웹 앱용 LDAP)

jooyons 2023. 6. 24. 09:01
반응형

서로 다른 인증 공급자와 함께 여러 WebSecurityConfigurerAdapter 사용(API용 기본 인증자 및 웹 앱용 LDAP)

Spring Security Reference 섹션 5.7에 따라 둘 이상의 보안 어댑터를 정의할 수 있어야 합니다.

저는 똑같이 하려고 노력하지만 성공하지 못합니다.서버 재부팅 후 처음 x배의 API는 기본 인증으로 정상적으로 작동하지만 몇 번 로그인(양식) 페이지로 리디렉션되면 API 호출이 아닌 우리 웹 앱에서만 이러한 현상이 발생합니다.

내 코드:

@EnableWebSecurity
public class MultiHttpSecurityConfig  {

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private Environment env;

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().
                withUser("admin").password("pw_test").roles(API_ROLE);
        }

        protected void configure(HttpSecurity http) throws Exception {
            http
              .antMatcher("/services/**")
              .authorizeRequests()
              .anyRequest().hasRole(API_ROLE)
              .and()
              .httpBasic()
              .and()
              .csrf()
              .disable();
        }
    }

    @Configuration
    @Order(2)
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private Environment env;

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
            auth.eraseCredentials(false);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // LDAP FORM AUTHENTICATION
            http.authorizeRequests()
                .antMatchers("/login.html").permitAll()
                .antMatchers("/css/**").permitAll() 
                .antMatchers("/js/**").permitAll() 
                .antMatchers("/images/**").permitAll() 
                .anyRequest().authenticated()
            .and().formLogin()
                .failureUrl("/login.html?error=1")
                .loginPage("/login.html")
                .loginProcessingUrl("/j_spring_security_check")
                .defaultSuccessUrl("/success.html")
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .permitAll();

            http.csrf().disable();

            // iFRAMES SETTINGS
            http
                .headers()
                .frameOptions().sameOrigin()
                .httpStrictTransportSecurity().disable();

            // HTTPS
            http
                .requiresChannel()
                .anyRequest()
                .requiresSecure();

            //MAP 8080 to HTTPS PORT
            http.portMapper().http(8080).mapsTo(443);
        }

        @Bean
        public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
            CustomLdapAuthenticationProvider provider = new CustomLdapAuthenticationProvider(env.getProperty("ldap.domain"), env.getProperty("ldap.url"), env.getProperty("ldap.base"));
            provider.setConvertSubErrorCodesToExceptions(true);
            provider.setUseAuthenticationRequestCredentials(true);
            return provider;
        }
    }
}

감 잡히는 게 없어요?

Spring Boot 버전 1.4.1-REASE와 Spring Security 버전 4.1.3-REASE를 사용하고 있습니다.

두 구성 모두에 동일한 구성을 사용합니다. 동일한 구성을 자동으로 배선하기 때문입니다.

Spring Security Architecture 참조:

@Configuration
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    ... // web stuff here

    @Autowired
    public void initialize(AuthenticationManagerBuilder builder, DataSource dataSource) {
        builder.jdbcAuthentication().dataSource(dataSource).withUser("dave")
            .password("secret").roles("USER");
    }

}

이 예는 웹 응용 프로그램과 관련이 있지만 사용 방법은AuthenticationManagerBuilder이 더 광범위하게 적용됩니다(웹 응용 프로그램 보안 구현 방법에 대한 자세한 내용은 아래 참조).참고:AuthenticationManagerBuilder이라@Autowired의 방법으로.@Bean이를 통해 글로벌(부모) Authentication Manager를 구축할 수 있습니다.이와 대조적으로 우리가 이런 식으로 했다면:

@Configuration
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    ... // web stuff here

    @Override
    public void configure(AuthenticationManagerBuilder builder) {
        builder.jdbcAuthentication().dataSource(dataSource).withUser("dave")
            .password("secret").roles("USER");
    }

}

(사용)@Override구성자에 있는 메서드의 경우).AuthenticationManagerBuilder"로컬"을 구축하는 데만 사용됩니다.AuthenticationManager그것은 세계적인 것의 아이입니다.

언급URL : https://stackoverflow.com/questions/40258583/using-multiple-websecurityconfigureradapter-with-different-authenticationprovide

반응형