programing

스프링 부트에서의 여러 Web Security Configurer Adapter 사용

minimums 2023. 3. 9. 21:55
반응형

스프링 부트에서의 여러 Web Security Configurer Adapter 사용

나는 2개의 수업을 듣고 있다.WebSecurityConfigurerAdapter그리고 같이 일하게 할 수 없다.

아이디어는 다음과 같습니다.

  1. 하나 드세요WebSecurityConfigurerAdapter보안 체인에만 커스텀필터를 추가합니다.필터는 몇 가지 커스텀 인증을 실시해,Authentication안으로SecurityContext이것은 일반적으로 정상적으로 동작합니다.다음과 같이 설정됩니다(imports 생략).
 @Order(1)
 @Configuration
 @EnableWebMvcSecurity
 public class BestSecurityConfig extends WebSecurityConfigurerAdapter {

     @Autowired
     private BestPreAuthenticationFilter ssoAuthenticationFilter;

     @Bean
     protected FilterRegistrationBean getSSOAuthenticationFilter() {
         FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(ssoAuthenticationFilter);

         // Avoid include to the default chain
         filterRegistrationBean.setEnabled(false);

         return filterRegistrationBean;
     }

     @Override
     protected void configure(HttpSecurity http) throws Exception {
         http
            .addFilterAfter(ssoAuthenticationFilter, SecurityContextPersistenceFilter.class);

     }

     @Configuration
     protected static class AuthenticationConfiguration extends
             GlobalAuthenticationConfigurerAdapter {

         @Autowired
         private BestAuthenticationProvider authenticationProvider;

         @Override
         public void configure(AuthenticationManagerBuilder auth) throws Exception {
             auth.authenticationProvider(authenticationProvider);
         }
     }
 }
  1. 나는 위와 같은 것들이 누구나 포함할 수 있는 도서관 수업이었으면 좋겠다.@ComponentScan커스텀 인증을 정렬합니다.커스텀을 제공하려고 하는 것이 분명합니다.HttpSecurityedpoints를 확보합니다.다음과 같은 시도를 합니다.
 @Configuration
 @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
 public class SecurityConfig extends WebSecurityConfigurerAdapter {

     @Override
     protected void configure(HttpSecurity http) throws Exception {
         http
             .csrf().disable()
             .authorizeRequests()
             .antMatchers("/testUrl").hasRole("NON_EXISTING")
             .anyRequest().authenticated();
     }
 }

내 사용자가 역할의 구성원이 아니므로 테스트 URL에 액세스할 수 없습니다.NON_EXISTING불행히도 그녀는 그렇다.

보안을 이동하면authorizeRequests()보안 필터를 추가하는 옆에 있는 구성 클래스 양식 1에 대한 부분. 그러면 예상대로 액세스가 차단됩니다.그러나 이 경우 두 번째 설정은 무시된 것으로 보입니다.

디버깅도 했어요configure()그 방법을 알게 되었습니다.HttpSecurity전혀 냄새가 나지 않는 물건입니다.

어떻게 하면 이 일을 높이 평가할 수 있을까요?

목표의 요약:

  • 을 가지다WebSecurityConfigurerAdapter필터가 추가되어 라이브러리 사용자로부터 숨겨집니다.
  • 사용자가 사용자 지정 엔드포인트 보안을 정의할 수 있습니다.

스프링 부트 1.1.6 릴리즈

특수 인터페이스를 정의합니다.

public interface ServiceWebSecurityConfigurer {
    void configure(HttpSecurity http) throws Exception;
}

다음으로 ConfigurerAdapter를 1개만 사용합니다.

public class MyConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Autowired(required = false)
    ServiceWebSecurityConfigurer serviceSecConfig;

    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests(). // whatever

        if (serviceSecConfig != null) serviceSecConfig.configure(http);

        http.authorizeRequests(). // whatever
    }
}

필요에 따라 Service Web Security Configurer를 다른 곳에 구현하기만 하면 됩니다.여러 구현이 있을 수도 있습니다.목록으로 자동 배선하고 반복하여 기본 구성에서 모두 사용합니다.

그래서 방금 찾은 한 가지 옵션은:

  1. 를 삭제합니다.@Configuration첫 번째 콩부터의 주석

그리고 2를 다음으로 변경합니다.

 @Configuration
 @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
 public class SecurityConfig extends BestSecurityConfig { //Note the changed extend !

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

         super.configure(http); // Merge of the 2 HTTP configurations

         http
             .csrf().disable()
             .authorizeRequests()
             .antMatchers("/testUrl").hasRole("NON_EXISTING")
             .anyRequest().authenticated();
     }
 }

이것이 옳은지 그른지에 대한 코멘트는 대단히 감사합니다.

편집: 몇 년이 지나도 여전히 다른 방법을 찾지 못했지만 점점 더 이 방식이 마음에 듭니다.디폴트의 경우에서도, 추상화를 확장합니다.WebSecurityConfigurerAdapter다른 추상화 계층이 의미 있는 기본값을 제공하는 또 다른 추상 확장을 제공하지 못할 이유가 없습니다.

커스텀 DSL사용하여 기본 구성을 보다 깔끔하게 구성하고 새로운 프로젝트에 쉽게 통합할 수 있는 방법을 찾았습니다.

JWT 인증 필터를 설정하는데 사용하고 있습니다만, CORS 필터가 보다 심플하고 교훈적이라고 생각합니다.

public class CustomCorsFilterDsl extends AbstractHttpConfigurer<CustomCorsFilterDsl, HttpSecurity> {

    @Override
    public void init(HttpSecurity http) throws Exception {
        //your init code here, no needed in this case
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        CorsFilter corsFilter = corsFilter(corsProperties);
        http.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class);
    }

    private CorsFilter corsFilter(CorsProperties corsProperties) {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:9000");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET, POST, PUT, PATCH, DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    public static CustomCorsFilterDsl dsl() {
        return new CustomCorsFilterDsl();
    }
}

Web Security Config 에서는 다음과 같이 사용할 수 있습니다.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .exceptionHandling()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/foo/**").permitAll()
                //... your configurations
                .antMatchers("/**").authenticated()
                .and()
                .apply(CustomCorsFilterDsl.dsl());
    }
}

프로젝트의 Web Security Config 커스텀 CORS 엔트리를 시각화할 수 있기 때문에 프로젝트 코드에 의존하지 않는 디폴트 구성의 라이브러리를 보다 명확하게 실현했습니다.

언급URL : https://stackoverflow.com/questions/26114269/using-multiple-websecurityconfigureradapter-in-spring-boot

반응형