Lamda DSL을 이용한 HttpSecurity, WebSecurity 구성 (SecurityFilterChain deprecated)

김세환·2023년 11월 1일
0

spring boot 3.1.3 버전으로 프로젝트 진행 중 기존 작성 방식대로 HttpSecurity 구성 시 오류가 발생 ('csrf()' is deprecated and marked for removal)

spring security 6.1 버전 이후로 기존 방식이 deprecated 되어서 Lamda DSL로 HttpSecurity와 WebSecurity를 구성해야 합니다.

Lamda DSL은 Spring Security 5.2 이후 도입된 방식으로 람다식으로 Security의 각 Configurer를 작성합니다.

이전 방식

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
        		.formLogin().disable() 
                .httpBasic().disable()  
                .csrf().disable()
                .headers().frameOptions().disable()
                
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)
                .and()

                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()

                .authorizeHttpRequests()

                .requestMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                
                .oauth2Login()
                .successHandler(oAuth2LoginSuccessHandler) 
            	.failureHandler(oAuth2LoginFailureHandler) 
            	.userInfoEndpoint().userService(customOAuth2UserService);
                .and()
                
                .apply(new JwtSecurityConfig(tokenProvider));
         
        return http.build();
}

기존의 경우 Configurer에 disable()이 아닌 경우 .and()를 사용해 체이닝을 해야 합니다. 또한 들여쓰기 구분이 명확하지 않아 가독성이 좋지 않습니다.

Lamda DSL Configuration

 @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .formLogin(AbstractHttpConfigurer::disable)// FormLogin 사용 X
                .httpBasic(AbstractHttpConfigurer::disable)// httpBasic 사용 X
                .csrf(AbstractHttpConfigurer::disable) // csrf 보안 사용 X
                .headers(httpSecurityHeadersConfigurer -> httpSecurityHeadersConfigurer
                        .frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))  //보안 헤더 설정
                .sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) //세션 사용 X
                .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                        .accessDeniedHandler(jwtAccessDeniedHandler))  //jwt 설정

                //접근 권한 설정
                .authorizeHttpRequests(authorize -> authorize

                        // 아이콘, css, js 관련
                        // 기본 페이지, css, image, js 하위 폴더에 있는 자료들은 모두 접근 가능, h2-console에 접근 가능
                        .requestMatchers("/").permitAll()
                        .requestMatchers("/","/css/**","/images/**","/js/**","/favicon.ico","/h2-console/**").permitAll()
                        .anyRequest().authenticated()) // 위의 경로 이외에는 모두 인증된 사용자만 접근 가능
                        
                /*oauth2 설정*/
                .oauth2Login(oauth2 -> oauth2
                        .successHandler(oAuth2LoginSuccessHandler)
                        .failureHandler(oAuth2LoginFailureHandler)
                        .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig
                                .userService(customOAuth2UserService))) //userService 설정

				//JwtFilter 를 addFilterBefore 로 등록했던 JwtSecurityConfig 클래스를 적용
                .apply(new JwtSecurityConfig(tokenProvider));  
        return http.build();
                
           
}

.and()를 사용한 메서드 체이닝에서 각 Configurer 마다 들여쓰기를 통해 설정을 구성합니다. 존재하는 메서드는 Method Reference 연산자로(::), 작업할 함수는 람다식(()->{}) 등으로 작성합니다.

장점

Lamda DSL을 사용할 경우,
명시적으로 .and()를 사용하지 않고 자동 들여쓰기를 통해 Configurer를 구분합니다.
따라서 개별 Configurer 마다 들여쓰기를 활용해 일관성 있는 Security 설정을 완료할 수 있습니다. 이는 더 좋은 가독성을 가지고 .and()를 사용한 체이닝이 아닌 Configurer 별로 설정을 구성할 수 있습니다.

출처

profile
Back-End Developer

0개의 댓글