Dazzling 개발 노트
[Spring] Spring Security란? 본문
1. Spring Security
- 스프링 기반의 애플리케이션의 보안(인증과 권한)을 담당하는 프레임워크
- 필터(Filter)를 기반으로 동작해 스프링 MVC와 분리되어 관리 및 동작한다.
- 필터(Filter)
- Dispatcher Servlet으로 가기 전에 적용되어 가장 먼저 URL 요청을 받지만, Interceptor는 Dispatcher와 Controller 사이에 위치한다.
- Client (Request) → Filter → DispatcherServlet → Interceptor → Controller
관련 용어
- Principal : 접근 주체
- 보호된 대상에 접근하는 유저
- Authentication : 인증
- 증명
- Authorization : 인가
- 권한 부여, 허가
- Role : 권한
- 인증된 주체가 애플리케이션의 동작을 수행할 수 있도록 허락되었는지를 결정할 때 사용
2. Spring Security Filter
- 스프링 MVC에서는 요청을 가장 먼저 받는 것이 DispatcherServlet이다.
- DispatcherServlet 전에 필터를 거친다.
- 필터를 통해 클라이언트와 자원 사이에서 요청과 응답 정보를 이용해 다양한 처리를 수행한다.
Security Filter Chain
- Spring Security에서 기본적으로 제공하는 다양한 기능을 가진 필터들을 의미
3. Spring Security 주요 모듈
유저가 로그인을 통해 인증을 성공
→ 인증 성공 시 principal과 credential 정보를 Authentication에 담는다.
→ Spring Security에서 Authentication을 SpringContext에 보관한다.
→ SpringContext를 SecurityContextHolder에 보관한다.
Authentication
- 현재 접근하는 주체의 정보와 권한을 담는 인터페이스
SecurityContext
- Authentication을 보관하는 역할
- SecurityContext를 통해 Authentication 객체를 꺼낼 수 있다.
SecurityContextHeader
- 보안 주체의 세부 정보를 포함해 응용프로그램의 현재 보안 컨텍스트에 대한 세부 정보 저장
UserDetails
- 인증에 성공해 생성된 객체
- Authentication 객체를 구현한 UsernamePasswordAuthenticationToken을 생성하기 위해 사용된다.
- implements하여 처리할 수 있다.
UserDetailsService
- UserDetails 객체를 반환하는 하나의 메서드 보유
- 보통 implements한 클래스에 UserRepository를 주입받아 DB와 연결해 처리
- DB에서 사용자 정보 조회
UsernamePasswordAuthenticationToken
- Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스
- Principal : User의 Id
- Credential : User의 Password
AuthenticationManager
- 인증 처리
- 인증에 성공 시 객체 생성
- SecurityContext에 생성한 객체를 저장
AuthenticationProvider
- 실제 인증 처리
- 인증 전의 Authentication 객체를 받아 인증이 완료된 객체 반환
4. Spring Security 인증 처리 과정
- 클라이언트가 로그인 시도
- AythenticationFilter에서 인증 처리
- UsernameAuthenticationToken 발급
- AuthenticationManager에게 인증 객체 전달
- 인증을 위해 AuthenticationProvider에게 인증 객체 전달
- 전달받은 인증 객체 정보를 UserDetailService에 전달
- UserDetails 구현 객체 생성
- UserDetails 객체를 AuthenticationProvider에 전달
- ProviderManager에게 권한을 담은 검증된 인증 객체 전달
- 검증된 인증 객체를 AuthenticationFilter에 전달
- 검증된 인증 객체를 SecurityContextHolder의 SecurityContext에 저장
5. 로그인한 사용자 정보 가져오기
Bean에서 사용자 정보 가져오는 방법
public static String getCurrentUserSolid(){
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = (User) principal;
Social social = currentUser.getSocial();
return social.getId();
}
Controller에서 사용자 정보 가져오는 방법
@PostMapping("product/create")
public Response createRecord(Principal principal){
}
@PostMapping("product/create")
public Response createRecord(Authentication authentication){
}
@AuthenticationPrincipal
Spring Security 3.2부터는 annotaion을 이용해 현재 로그인한 사용자 객체를 인자에 주입할 수 있다.
@PostMapping("product/create")
public Response createRecord(@AuthenticationPrincipal UserDetails userDetails){
}