본문 바로가기
개발자 로그

🔐 Spring Security - 엔드포인트 수준에서 인가 적용하기

by Hello_World_! 2025. 7. 29.
반응형

✅ 사용자 관리 이후, 인증/인가 설정 확장하기

엔드포인트별 인증 및 인가 처리 방식을 설정할 수 있습니다.

기본적으로 Spring Security는 모든 요청에 대해 인증을 요구합니다. 기본 인증 방식은 HTTP Basic Authentication이며, 대부분의 실제 애플리케이션에서는 다른 방식으로 변경이 필요합니다.

🔧 인증/인가를 제어하기 위한 핵심: SecurityFilterChain Bean

Spring Security에서 인증과 인가를 커스터마이징하려면 SecurityFilterChain을 직접 설정해야 합니다.

📌 예제 1: 기본 인증 방식 유지 (anyRequest().authenticated())

@Configuration
public class ProjectConfig {

  @Bean
  SecurityFilterChain configure(HttpSecurity http) throws Exception {
    http.httpBasic(Customizer.withDefaults());
    http.authorizeHttpRequests(
      c -> c.anyRequest().authenticated() //중요
    );
    return http.build();
  }
}

→ 모든 요청에 대해 인증이 필요합니다. 이는 기본 동작과 동일한 설정입니다.

📌 예제 2: 모든 요청 인증 없이 허용 (permitAll())

@Configuration
public class ProjectConfig {

  @Bean
  public SecurityFilterChain configure(HttpSecurity http) throws Exception {
    http.httpBasic(Customizer.withDefaults());
    http.authorizeHttpRequests(
      c -> c.anyRequest().permitAll()
    );
    return http.build();
  }
}

→ 모든 엔드포인트를 인증 없이 누구나 접근 가능하게 설정한 예제입니다.

📥 테스트 시:

curl http://localhost:8080/hello

응답:

Hello!

📘 용어 및 개념 설명

메서드 설명
http.httpBasic() HTTP Basic 인증 방식 사용 선언
authorizeHttpRequests() 요청 경로별 인가 설정 (예: 인증 필요 여부)
Customizer.withDefaults() 설정 없이 기본값으로 처리

📉 예전 방식과의 차이

이전(Spring Security 5 이전)에는 WebSecurityConfigurerAdapter를 상속하여 설정했습니다:

http.authorizeHttpRequests()
    .anyRequest().authenticated();

현재는 더 유연하고 명시적인 방식으로 전환되어, 테스트와 유지보수가 쉬워졌습니다.

🧩 사용자 설정 방식의 또 다른 예시

SecurityFilterChain 내부에서 사용자 정보를 직접 선언할 수도 있습니다:

@Configuration
public class ProjectConfig {

  @Bean
  public SecurityFilterChain configure(HttpSecurity http) throws Exception {
    http.httpBasic(Customizer.withDefaults());
    http.authorizeHttpRequests(
      c -> c.anyRequest().authenticated()
    );

    var user = User.withUsername("john")
                   .password("12345")
                   .authorities("read")
                   .build();

    var userDetailsService = new InMemoryUserDetailsManager(user);
    http.userDetailsService(userDetailsService);

    return http.build();
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return NoOpPasswordEncoder.getInstance();
  }
}

이처럼 사용자와 UserDetailsService를 SecurityFilterChain 내부에서 선언하면 외부 @Bean 없이 로컬 구성으로 설정할 수 있습니다.

🔄 두 가지 구성 방식 비교

방법 특징
@Bean으로 따로 분리 여러 클래스에서 재사용 가능, 테스트 용이
SecurityFilterChain 내부 정의 간단한 앱이나 예제에서 코드 집중화 가능

✅ 요약

  • SecurityFilterChain은 Spring Security 인증/인가 설정의 핵심입니다.
  • 인증 방식은 http.httpBasic(), 인가 규칙은 authorizeHttpRequests()로 설정합니다.
  • Customizer.withDefaults()는 기본 동작을 의미합니다.
  • permitAll()을 통해 모든 요청을 인증 없이 허용할 수 있습니다.
  • 사용자 정의는 외부 @Bean 등록 방식과 내부 구성 방식 두 가지가 존재합니다.