강의

멘토링

로드맵

Inflearn Community Q&A

potatomango's profile image
potatomango

asked

Microservice Application (MSA) Development with Spring Cloud

Users Microservice - Spring Security Integration

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

Written on

·

9.9K

·

Edited

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-bootarchitecturespring-securityspring-cloudconfigJPAmsaKafka

Answer 7

4

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

potatomango님의 프로필 이미지
potatomango
Questioner

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

1

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

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

 

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

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

potatomango님의 프로필 이미지
potatomango
Questioner

공유 감사합니다~

0

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

0

Wow 감사합니다 ㅎㅎㅎ

0

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

potatomango's profile image
potatomango

asked

Ask a question