Hyun_dev

Spring Security 기본 알아보기

5/6/2025

Spring Security 내부 흐름도를 알아 보자

spring-security-internal-flowspring-security-internal-flow

  • 내부 흐름도는 위 이미지와 같다.
  • Authentication Manager-> Authentication Providers 내부 에서 일어나는 흐름을 이해하는 것이 중요하다.
    • 해당 포스트에서는 Spring Security 기본 설정에 대해서 주요하게 서술할 예정이다.

Spring Security Framework 내의 기본 구성을 확인해보자.

  • SpringBootWebSecurityConfiguration 파일을 확인해보자.
  • 내부 파일을 확인 해보면, 아래처럼 이렇게 기본적으로 정의가 되어있는 것을 확인할 수 있다.
@Bean
@Order(SecurityProperties.BASIC_AUTH_ORDER)
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {

    http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
    http.formLogin(withDefaults());
    http.httpBasic(withDefaults());
    return http.build();
}
  • 여기서는 현재 웹 애플리케이션으로 들어오는 모든 요청을 익명 사용자가 API에 접근하지 못하도록 보안을 설정하고 있다.
  • formLogin() 메서드는 기본적으로 UsernamePasswordAuthenticationFilter와 연결되어 있다
  • httpBasic() 메서드는 BasicAuthenticationFilter와 연결되어 있다.
    • HTTP 프로토콜에 사용자 이름과 비밀번호를 함께 담아서 요청하는 인증방식이며, Base64로 인코딩한 값이다. (암호화는 아니다)

요구사항에 따라 Spring Security 설정하기

  • 필요한 설정은 두 가지이다.
application.properties
spring.security.user.name=user
spring.security.user.password=12345
ProjectSecurityConfig
@Configuration
public class ProjectSecurityConfig {
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((requests) -> requests
                .requestMatchers("/urlA").authenticated()
                .requestMatchers("/urlB", "/error").permitAll());
        http.formLogin(withDefaults());
        http.httpBasic(withDefaults());
        return http.build();
    }
}
  • 해당 파일에서 urlA, urlB를 각각 다르게 설정한 것을 볼 수 있는데, requestMatchers를 활용하여 요구사항에 맞게 커스텀하여 보안 인증이 필요한 페이지와 그렇지 않은 페이지를 구분할 수 있다.
  • /error 페이지 같은 경우는 기본적으로 Spring Security에서 지원하는 페이지이며, 기본은 authenticated() 상태이기 때문에 필요에 따라 permitAll()로 설정할 수 있다.
  • 또한, formLogin, httpBasic을 비활성화 하고 싶다면 아래처럼 수정할 수 있다.
http.formLogin(flc -> flc.disable());
http.httpBasic(hbc -> hbc.disable());
  • 이렇게 disable()을 지정하여 필요에 따라 비활성화를 할 수 있다.
  • formLogin()을 비활성화할 시에는, 기본 인증이 httpBasic()이기 때문에, 웹 브라우저의 팝업 창으로 자격 증명을 진행한다.
  • 만약, 둘 다 비활성화를 한다면 브라우저가 아무런 단서를 찾지 못하기 때문에 403 에러를 반환한다.