yeon's blog

[Spring] Spring Security 개념 본문

Spring/Spring 개념

[Spring] Spring Security 개념

yeonii 2023. 12. 12. 16:57

1. Spring Security 개념

스프링 기반의 애플리케이션의 보안(인증과 권한)을 담당하는 프레임워크

 

스프링 시큐리티는 필터(Filter) 기반으로 동작하기 때문에 스프링 MVC와 분리되어 관리 및 동작한다.

필터(Filter)는 Dispatcher Servlet으로 가기 전에 적용되므로 가장 먼저 URL 요청을 받지만, Interceptor는 Dispatcher와 Controller 사이에 위치한다. 그래서 이 둘은 적용 시기에 차이점이 있다.

 

Client (request) -> Filter -> DispatcherServlet -> Interceptor -> Controller

 

Spring Security 3.2버전 부터는 자바 config 설정으로 간단하게 설정할 수 있다. (XML 설정 X)

 

[용어]

* 접근 주체(Principal): 보호된 대상에 접근하는 유저

* 인증 (Authentication): 해당 사용자가 본인이 맞는지를 확인하는 절차

* 인가 (Authorization): 인증된 사용자가 요청된 자원에 접근 가능하지 불가능한지를 결정하는 절차
* 권한 (Role)
: 인증된 주체가 애플리케이션의 동작을 수행할 수 있도록 허락되어 있는지를 결정할 때 사용

 

2. Spring Security Filter

 

위에서 스프링 MVC에서는 요청을 가장 먼저 받는 것이 DispatcherServlet이라고 했다. 그리고 이 DispatcherServlet이 요청을 받기 전에 다양한 필터가 있을 수 있다.

 

필터가 하는 역할은 클라이언트와 자원 사이에서 요청과 응답 정보를 이용해 다양한 처리를 하는데 목적이 있다.

 

 

✔️ Security Filter Chain

Spring Security는 다양한 기능을 가진 필터들을 10개 이상 기본적으로 제공한다.

제공되는 필터들을 Spring Filter Chain (시큐리티 필터 체인)이라고 한다.

 

 

3. Spring Security 주요 모듈

[ Authentication ]

현재 접근하는 주체의 정보와 권한을 담는 인터페이스

 

[ SecurityContext ]

Authentication을 보관하는 역할을 하며, SecurityContext를 통해 Authentication 객체를 꺼내올 수 있음

 

[ SecurityContextHolder ]

보안 주체의 세부 정보를 포함하여 응용프로그램의 현재 보안 컨텍스트에 대한 세부 정보 저장

 

* 로그인 후 과정

인증에 성공하면 principal과 credential 정보를 Authentication에 담는다.

→ Spring Security에서 Authentication을 SpringContext에 보관한다.

→ 이 SpringContext를 SecurityContextHolder에 담아 보관한다.

 

 

[ UserDetails ]

인증에 성공하여 생성된 UserDetails 객체는 Authentication 객체를 구현한 UsernamePasswordAuthenticationToken을 생성하기 위해 사용된다. UserDetails를 implements 하여 처리할 수 있다.

 

*현재 프로젝트에서 CustomUserDetails로 구현하여 UserDetails를 implements 하였다.

 

[ UserDetailsService ]

UserDetailsService는 UserDetails 객체를 반환하는 하나의 메서드만을 가지고 있는데, 일반적으로 이를 implements 한 클래스에 UserRepository를 주입받아 DB와 연결하여 처리한다.

즉, 이곳에서 DB의 사용자 정보를 조회한다.

 

* 현재 프로젝트에서 CustomUserDetailsService로 구현하였다.

Instagram 서비스에서 Adaptor를 사용하고 있기 때문에 UserAdaptor를 주입받았다.

 

[ UsernamePasswordAuthenticationToken ]

Authentication을 implements 한 AbstractAuthenticationToken의 하위 클래스로, User의 ID가 Principal 역할을 하고, Password가 Credential 역할을 한다.

UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두 번쨰는 인증이 완료된 객체를 생성한다.

 

[ AuthenticationManager ]

인증에 대한 부분은 AuthenticationManager를 통해 처리하게 되는데, 실질적으로는 AuthenticationManager에 등록된 AuthenticaionProvider에 의해 처리된다.

 

[ AuthenticationProvider ]

AuthenticationProvider에서는 실제 인증에 대한 부분을 처리하는데, 인증 전의 Authentication 객체를 받아서 인증이 완료된 객체를 반환하는 역할을 한다.