Programing/Spring Security

Spring Starter security 2.x 3.x 설정 방식 차이

리커니 2023. 11. 21.
반응형

이번 포스팅에서는 Spring 2.x 와 3.x 의 설정 방식의 차이에 대해서 알아보겠습니다.

JWT 를 쓰는 환경이고, 같은 설정 코드를 비교해서 어떤 점이 달라졌는지 확인해보겠습니다.

 

2.x 설정 코드 입니다.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig {
    private final TokenProvider tokenProvider;
    private final JwtAuthenticationEntryPoint jwtAtuthenticationEntryPoint;
    private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
        @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .csrf().disable()
                .cors().disable()

                /* 401, 403 Exception 핸들링 */
                .exceptionHandling()
                .authenticationEntryPoint(jwtAtuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)

                /* 세션 사용하지 않음 */
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                /* HttpServletRequest를 사용하는 요청들에 대한 접근 제한 설정 */
                .and()
                .authorizeHttpRequests()
                .antMatchers(CmmnVar.ignoreUrls).permitAll()
                /* swagger 관련 허용 */
                .antMatchers(CmmnVar.swaggerUrls).permitAll()
                .anyRequest().authenticated()

                /** JwtSecurityConfig 적용 */
                .and()
                .apply(new JwtSecurityConfig(tokenProvider))
                .and().build();
    }
}

 

 

3.x 설정 코드 입니다.

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {
    private final TokenProvider tokenProvider;
    private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
    private final MessageConfig messageConfig;
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(AbstractHttpConfigurer::disable)
            .cors(AbstractHttpConfigurer::disable)
            .headers(c -> c.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable).disable())
            .authorizeHttpRequests(auth -> {
                auth
                    .requestMatchers(CommonVariables.ignoreUrls).permitAll()
                    .requestMatchers(CommonVariables.swaggerUrls).permitAll()
                    .anyRequest().authenticated();
            }).exceptionHandling(c ->
                    c.authenticationEntryPoint(jwtAuthenticationEntryPoint).accessDeniedHandler(jwtAccessDeniedHandler)
            ).sessionManagement(c -> c.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .apply(new JwtSecurityConfig(tokenProvider, messageConfig));
        return http.build();
    }
}

 

위에서 부터 천천히 보시면 3.x 에서는 @EnableGlobalMethodSrcurity 가 Deprecated 되었습니다.

해당 어노테이션은 메서드 기반의 시큐리티를 적용할 수 있는 옵션을 제공합니다. 

 3.x 에서는 @EnableMethodScurity 로 이를 대체합니다.

 

passwordEncoder 설정이나 다른 방식은 크게 차이가 없지만,

filterChain method를 보시면 HttpSecurity의 메서드 호출 방식이 변경 되었습니다.

csrf method를 비교해보겠습니다.

 

2.x

public CsrfConfigurer<HttpSecurity> csrf() throws Exception {
    ApplicationContext context = getContext();
    return getOrApply(new CsrfConfigurer<>(context));
}

 

3.x

public HttpSecurity csrf(Customizer<CsrfConfigurer<HttpSecurity>> csrfCustomizer) throws Exception {
    ApplicationContext context = getContext();
    csrfCustomizer.customize(getOrApply(new CsrfConfigurer<>(context)));
    return HttpSecurity.this;
}

 

이와 같이 거의 모든 메서드가 매개변수를 받아 처리하는 함수형 방식으로 변경이 되면서 좀 더 유연하고 간결하게 설정할 수 있도록 변경 되었습니다.

반응형

댓글

💲 추천 글