저번 프로젝트에서 SpringSecurity를 적용해서 개발했었다. 이번에 글로 적으면서 정리해보자!!
SpringSecurity란?
스프링 기반의 애플리케이션의 보안(인증과 권한, 인가 등)을 담당하는 스프링 하위 프레임워크
사이트에 대해서 유효한 사용자인지 확인하는 것이 인증 이고, 인증된 사용자가 사용할 수 있는 기능인지 확인하는게 인가 따라서 인증이 먼저 이루어 지고 인가가 이뤄져야 한다.
Spring Security 에서는 이러한 인증, 인가를 위해 Principal 을 아이디로 Credential 을 비밀번호로 사용하는 Credential 기반의 인증 방식을 사용한다.

Spring Security 특징
- Filter 기반으로 동작하기 때문에(AOP) Spring MVC와 분리되어 관리 및 동작한다.
- 세션 - 쿠기 방식으로 인증
- 스프링의 DispatcherServlet 앞단에 Filter 형태로 위치
- Dispathcer로 넘어가기 전에 이 Filter가 요청을 가로채서 클라이언트의 리소스 접근 권한을 확인하고 없는 경우에는 인증 요청 화면으로 자동 다이렉트
Spring Security 모듈

SecuirtyContextHolder
- SecurityContextHolder는 SecurityContext를 제공하는 static 메소드(getContext)를 지원한다.
SecurityContext
- SecurityContext는 접근 주체와 인증에 대한 정보를 담고 있는 Context다.
- 즉, Authentication을 담고있다.
Authentication
- Principal과 GrantAuthority를 제공한다.
- 인증이 이루어지면 해당 Authentication이 SecurityContext에 저장된다.
- SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근할 수 있다.
Principal
- 유저에 해당하는 정보다.
- 대부분의 경우 Principal로 UserDetails를 반환한다.
GrantAuthority
- ROLEADMIN, ROLE_USER 등 Principal이 가지고 있는 권한을 나타낸다.
- prefix로 'ROLE'이 붙는다.
- 인증 이후에 인가를 할 때 사용한다.
- 권한은 여러개일 수 있기 때문에 Collection<(GrantedAuthority)> 형태로 제공한다.
ex) ROLE_DEVELOPER, ROLE_ADMIN
UsernamePasswordAuthenticationToken
- Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스다.
- User의 ID가 Principal 역할을 하고, Password가 Credential의 역할을 한다.
- UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두 번째 생성자는 인증이 완료된 객체를 생성한다.
Authentication Provider
- Authentication Provider에서는 실제 인증에 대한 부분을 처리한다.
- Authentication 객체를 받아서 인증이 완료된 객체를 반환하는 역할을 한다.
- Authentication Provider 인터페이스를 구현해서 Custom한 Authentication Provider을 작성하고, AuthenticationManager에 등록하면 된다.
Authentiaction Manager
- 인증에 대한 부분은 SpringSecurity의 Authentication Manager를 통해서 처리하게 되는데, 실질적으로는 Authentication Manager에 등록된 Authentication Provider에 의해서 처리된다.
- 인증이 성공하면 2번째 생성자를 이용해 인증이 성공한 객체를 생성하여 Security Context에 저장한다.
- 인증 상태를 유지하기 ㅜ이해 세션에 보관하고, 인증이 실패하면 AuthenticationException을 발생시킨다.
UserDetails
- 인증에 성공하여 생성된 UserDetails 객체는 Authentication 객체를 구현 UsernamePasswordAuthentication을 생성하기 위해 사용된다.
UserDetailsService
- UserDetailsService 인터페이스는 UserDetails 객체를 반환하는 단 하나의 메소드를 가지고 있다.
- 일반적으로 이를 구현한 클래스의 내부에 UserRepository를 주입받아 DB와 연결하여 처리한다.
PasswordEncoding
- AuthenticationManagerBuilder.userDetailsService().passwordEncoder()를 통해 패스워드 암호화에 사용될 PasswordEncoder 구현체를 지정할 수 있다.
Spring Security Architecutre

- 사용자가 로그인 정보와 함께 인증 요청을 한다.(Http Request)
- AuthenticationFilter가 요청을 가로채고, 가로챈 정보를 통해 UsernamePasswordAuthenticationToken의 인증용 객체를 생성한다.
- AuthenticationManager의 구현체인 ProviderManager에게 생성한 UsernamePasswordToken 객체를 전달한다.
- AuthenticationManager는 등록된 AuthenticationProvider(들)을 조회하여 인증을 요구한다.
- 실제 DB에서 사용자 인증정보를 가져오는 UserDetailsService에 사용자 정보를 넘겨준다.
- 넘겨받은 사용자 정보를 통해 DB에서 찾은 사용자 정보인 UserDetails 객체를 만든다.
- AuthenticationProvider(들)은 UserDetails를 넘겨받고 사용자 정보를 비교한다.
- 인증이 완료되면 권한 등의 사용자 정보를 담은 Authentication 객체를 반환한다.
- 다시 최초의 AuthenticationFilter에 Authentication 객체가 반환된다.
- Authenticaton 객체를 SecurityContext에 저장한다.
최종적으로 SecurityContextHolder는 세션 영역에 있는 SecurityContext에 Authentication 객체를 저장한다. 사용자 정보를 저장한다는 것은 Spring Security가 전통적인 세션-쿠키 기반의 인증 방식을 사용한다는 것을 의미한다.