본문 바로가기
Dev/SpringBoot

[SpringSecurity] 실습#2

by 컴포넌트설계자 2026. 5. 27.

 

각 단계를 클릭하면 해당 단계에 대한 추가 설명을 물어볼 수 있어요. 흐름을 간단히 요약하면:

요청 → 인증 객체 생성 → 위임 → 검증 → UserDetails 반환 → SecurityContext 저장 → Controller 활용

핵심 포인트 세 가지:

  • UsernamePasswordAuthenticationFilter는 진입점 — 폼 데이터를 받아 Authentication 미완성 객체를 만들고 넘깁니다.
  • UserDetailsService가 실제 DB 조회를 담당 — 여기서 loadUserByUsername()을 직접 구현하게 됩니다.
  • 인증 완료 후엔 SecurityContextHolder.getContext().getAuthentication()으로 어디서든 유저 정보에 접근할 수 있습니다.

service랑 레포지토리는 root.web.application 에서 만들어야 한다.

 

앞서 설명한 인증 흐름과 연결해서 왜 Service와 Repository를 반드시 Root WebApplicationContext에 등록해야 하는지를 정리하면 이렇습니다.


핵심 이유 — Spring Security 필터는 DispatcherServlet 앞에서 동작한다

인증 흐름 5단계의 UserDetailsService와 AuthenticationManager는 Spring Security Filter Chain 안에서 호출됩니다. 그런데 이 필터 체인은 HTTP 요청이 DispatcherServlet에 도달하기 전에 실행됩니다. 즉, 필터가 동작하는 시점에는 Servlet WebApplicationContext가 아직 개입하지 않은 상태입니다.

Spring 컨텍스트 계층 규칙에 따르면:

  • Root WebApplicationContext → 애플리케이션 전역, 모든 서블릿이 공유
  • Servlet WebApplicationContext → DispatcherServlet 전용, Root Context의 빈은 참조 가능하지만 역방향은 불가

따라서 Security Filter Chain은 Root Context의 빈만 참조할 수 있습니다.


만약 Service를 Servlet Context에 등록하면?

UserDetailsService를 @Controller처럼 Servlet Context에 등록했다고 가정하면:

  1. UsernamePasswordAuthenticationFilter 실행 (Root Context 레벨)
  2. AuthenticationProvider가 UserDetailsService 빈을 Root Context에서 찾음
  3. 빈이 없음 → NoSuchBeanDefinitionException 또는 인증 실패

결론적으로 등록 위치 정리

빈등록 위치이유
Controller, ViewResolver Servlet Context DispatcherServlet 전용 웹 빈
Service, Repository Root Context Security Filter + Controller 양쪽에서 접근 필요
UserDetailsService, AuthenticationManager Root Context 필터 체인이 이 레벨에서 동작

'Dev > SpringBoot' 카테고리의 다른 글

[SpringSecurity] 실습#1  (0) 2026.05.27
JSP/Servlet의 3가지 Scope  (0) 2026.05.26