inflearn logo
강의

Course

Instructor

Microservice Application (MSA) Development with Spring Cloud

Users Microservice - Spring Security Integration

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

10068

potatomango

3 asked

18

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

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();
    }

}

 

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

spring-boot architecture spring-security spring-cloud config JPA msa Kafka

Answer 7

4

yellowsunn

감사합니다! 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)

0

potatomango

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

1

rabbit125834668

boot 3.3.5 기준

 

@Configuration
@EnableWebSecurity
public class WebSecurity {

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

    @Bean
    public SecurityFilterChain config(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable) // CSRF 비활성화
                .headers(headers -> headers
                        .frameOptions(HeadersConfigurer.FrameOptionsConfig::disable) // X-Frame-Options 비활성화
                )
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(WHITE_LIST).permitAll() // 특정 경로 허용
                        .anyRequest().authenticated()); // 나머지 요청은 인증 필요
        return http.build();
    }
}

1

zecrar6005

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

 

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

kgh1986213527

@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 설정 부분에서 람다식을 이용하여 메소드 체이닝으로 좀 더 간결하게 작성 할 수 있습니다

0

potatomango

공유 감사합니다~

0

bascat

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

0

progress0407

Wow 감사합니다 ㅎㅎㅎ

0

21jongg

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

kafka 업데이트 강의 듣고 시포요

0

83

1

강의 교안

0

71

1

마이크로서비스간 통신 시, 인증 처리

0

79

1

api gateway 에서 인증 처리

0

64

1

섹션 19 질문드립니다

0

51

1

강의 자료 업데이트

0

81

1

부하분산 강의 섹션

0

56

1

강의자료는 어디에서?

0

69

1

강의 자료는 어디서 다운 받을 수 있나요?

0

109

1

전체 사용자 조회시 오류

0

57

1

혹시 pk 외 별도의 id 를 부여한 이유가 있을까요 ??

0

108

2

학습 방향

0

94

2

카프카 커넥터 사용 목적 문의

0

85

2

kafka 강의

0

106

2

서비스 디스커버리 종류

0

86

2

강의 자료에 대해서 궁금해요

0

115

2

GlobalFilter, LoggingFilter가 동작하지 않습니다.

0

89

2

Kafka Source Connect 버전 에러

0

83

2

소스커넥터는 사용안한 거 맞죠?

0

81

2

강의자료 업데이트 문의

0

94

2

강의에서 BCryptPasswordEncoder 에 역할(5-2)

0

56

1

강의 업데이트 계획이 궁금합니다.

0

111

2

MSA 애플리케이션에 Spring Web과 Spring Data JPA를 사용하는 것이 바람직한지 궁금합니다. (MSA 설계와 관련된 질문입니다)

0

160

2

어떤 것이 업데이트 된 건가요?

0

162

2