(이 포스트는 우테코 테코톡 영상 - Spring Security 편의 내용을 정리하기 위해서 작성했습니다.)

 

Spring Security는 내부적으로 여러 클래스와 인터페이스들을 거침으로써 웹에서 인증(Authentication)과 인가(Authorization) 작업을 쉽게 구현할 수 있도록 한다. 

 

Spring Security 구조

내부 구조는 크게 보면 다음과 같다. 

1. AuthenticationFilter

2. AuthenticationManager

3. AuthenticationProvider

4. UserDetailsService

5. UserDetails

6. SecurityContextHolder

 

(1) AuthenticationFilter

Spring Security의 구조를 크게 살펴보면, 들어온 요청은 제일 먼저 AuthenticationFilter를 거친다. AuthenticationFilter에서는 앞으로의 인증 과정에서 사용하기 위해 UsernamePasswordAuthenticationToken(일종의 토큰으로 보면 된다)을 만들고, 이를 다음 단계인 AuthenticationManager 인터페이스에 전달한다. 

나중에는 AuthenticationManager로부터 인증이 완료된 User 객체를 받아서 SecurityContextHolder에 전달하는 역할까지 맡는다. 

(SecurityContextHolder는 스프링 시큐리티의 In-Memory DB라고 보면 된다.)

 

(2) AuthenticationManager

AuthenticationManager는 사실 인터페이스이고, 이를 구현한 클래스로는 ProviderManager가 있다. 이 인터페이스/구현 클래스에서는 AuthenticationFilter에서 넘어온 토큰이 유효한지 확인한 뒤(validate token credentials) 다음 단계인 AuthenticationProvider로 넘겨준다. 

 

(3) AuthenticationProvider

인증 작업이 이뤄지는 단계다. 토큰의 정보가 인증 서버에 있는 credentials 정보와 일치하는지를 검사한다. 일치하지 않으면 AuthenticationException을 발생시키고, 일치한다면 Authentication 토큰 객체에 추가 정보를 담는다. 

 

(4) UserDetailsService

이름처럼 UserDetails의 서비스 클래스라고 이해했다. 인증이 완료된 토큰을 UserDetails 인터페이스에게 넘겨준다. 

 

(5) UserDetails

인터페이스로, User 클래스가 이를 구현한다. UserDetailsService에서 받은 토큰의 정보를 사용해서 인증 서버나 일반 DB에서 유저 정보를 조회한다. 그렇게 조회된 User 객체를 다시 UserDetailsService에 전달한다.

이 User 객체는 (4), (3), (2), (1)을 거쳐서 (6)의 SecurityContextHolder로 전달된다. 

 

(6) SecurityContextHolder

스프링 시큐리티에서 사용하는 인메모리 저장소로 볼 수 있는데, SecurityContextHolder 안 SecurityContext 안 Authentication 부분에 인증 관련 정보들이 저장된다. 

그리고 유저 상태를 authenticated로 바꾼 뒤 요청을 DispatcherServlet에게 넘긴다. 그러면 DispatcherServlet에서 유저가 원래 요청했던 URL에 해당하는 컨트롤러의 메소드를 호출하여 응답을 리턴하게 된다. 

 

참고한 컨텐츠

https://www.youtube.com/watch?v=aEk-7RjBKwQ 

 

+ Recent posts