• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Spring Boot 최신 3.XX 버전 Security 설정 공유드립니다.

23.02.17 11:10 작성 23.02.17 11:12 수정 조회수 8.01k

16

최신 버전 진행하시는 분들을 위해 공유드립니다.

Spring Security Configuration 설정 내용이 변경되었습니다. WebSecurityConfigurerAdapter 클래스가 deprecated되었는데요. 해당 클래스를 상속 받아 config 메소드를 구현하는 대신 SecurityFilterChain을 반환하고 직접 Bean으로 등록하도록 설정 방법이 바뀌었습니다.

 

package com.example.userservice.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class WebSecurity {

    private static final String[] WHITE_LIST = {
            "/users/**",
            "/**"
    };

    @Bean
    protected SecurityFilterChain config(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().frameOptions().disable();
        http.authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(WHITE_LIST).permitAll());
        return http.build();
    }

}

 

강의 내용을 진행하기 위해서 강의에 나온 설정을 위처럼 설정해보았는데요. 일단 이렇게 설정하면 강의를 진행하는데 문제 없을 것이니 참고 바랍니다~

답변 6

·

답변을 작성해보세요.

4

yellowsunn님의 프로필

yellowsunn

2023.02.19

감사합니다! pattern /** 은 모든 경로에 대해서 허용해주는게 조금 아쉬어서 h2 에 대해서만 추가로 적용되게 찾아봤는데요.
h2의 경우 pattern "/h2-console" 등록을 해도 403으로 뜨는데 PathRequest.toH2Console() 을 사용하면 자동으로 올바른 경로를 찾아주네요.

@Bean
protected SecurityFilterChain config(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.headers().frameOptions().disable();
    http.authorizeHttpRequests(authorize -> authorize
        .requestMatchers("/users/**").permitAll()
          .requestMatchers(PathRequest.toH2Console()).permitAll()
    );
    return http.build();
}

(참고자료:https://docs.spring.io/spring-boot/docs/current/reference/html/data.html#data.sql.h2-web-console.custom-path)

이강민님의 프로필

이강민

질문자

2023.03.02

좋은 정보 공유해주셔서 감사합니다~ 저도 추가적인 설정이 필요하겠다 생각은 하고 있었는데 이런 해결 방법이 있는 줄 몰랐네요. H2에만 적용할 수 있는 기능이 있다니 덕분에 좋은 지식을 얻었습니다!

1

고기님의 프로필

고기

2024.02.16

부트 버전이 올라가서 코드가 또 수정된것 같네요

 

return http
                .csrf(AbstractHttpConfigurer::disable)
                .headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
                .authorizeHttpRequests(
                        authorize -> authorize
                                .requestMatchers(WHITE_LIST).permitAll()
                                .requestMatchers( PathRequest.toH2Console()).permitAll()
                )
                .build();

 

 

1

코난님의 프로필

코난

2023.05.22

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http.csrf().disable()
            .headers(authorize -> authorize
                    .frameOptions().disable())
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers(WHITE_LIST).permitAll()
                    .requestMatchers(PathRequest.toH2Console()).permitAll())
            .getOrBuild();
}

추가적으로 security 설정 부분에서 람다식을 이용하여 메소드 체이닝으로 좀 더 간결하게 작성 할 수 있습니다

이강민님의 프로필

이강민

질문자

2023.05.23

공유 감사합니다~

0

SS님의 프로필

SS

2023.10.15

Spring Boot 3.0 기준으로 변경된 사항이 많네요. 공유 감사합니다!

0

필로님의 프로필

필로

2023.05.05

Wow 감사합니다 ㅎㅎㅎ

0

21jongg님의 프로필

21jongg

2023.03.07

와우.. 두분 다 정말 감사합니다. 덕분에 방법도 빠르게 찾고, 이런 방법도 알게되어서 감사합니다.