Programming/Java

[Java Spring] Spring Security의 개념 및 처리 과정

erinh 2023. 1. 24. 17:00
반응형

들어가기에 앞서

인증(Authentication)과 인가(Authorization)

- 인증(Authentication) : 해당 사용자가 본인이 맞는지 확인하는 과정

- 인가(Authorization) : 해당 사용자가 요청하는 자원을 실행할 수 있는 권한이 있는가를 확인하는 과정

➡️ Spring Security는 인증 절차를 거친 후 인가 절차를 진행

➡️ Principal을 아이디로 Credential을 비밀번호로 사용하는 Credential 기반 인증 방식 사용

  • Principal(접근 주체) : 보호 받는 Resource에 접근하는 대상
  • Credential(비밀번호) : Resource에 접근하는 대상의 비밀번호

Spring Security란?

: Spring 기반의 어플리케이션 보안(인증과 권한, 인가 등)을 담당하는 스프링 하위 프레임워크

- 인증과 권한에 대한 부분을 Filter 흐름에 따라 처리

Client(request) → Filter → DispatcherServlet → Interceptor → Controller

Spring Security Architecture

1. 사용자가 로그인 정보와 함께 인증 요청 (Http Request)

2. AuthenticationFilter가 요청을 가로채고 가로챈 요청을 통해 UsernamePasswordAuthenticationToken의 인증용 객체 생성
 - UsernamePasswordAuthenticationToken은 Authentication을 implements한 AbstractAuthenticationToken의 하위클래스
 - User의 ID가 Principal, Password가 Credential 역할을 함
 - UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성, 두 번째는 인증 완료된 객체를 생성

3. AuthenticationManager의 구현체인 ProviderManager에게 생성한 UsernamePasswordToken 객체 전달

 - 인증에 대한 부분은 AuthenticationManager을 통해서 처리(실질적으로는 AuthenticationManager에 등록된 AuthenticationProvider에 의해 처리)
 - 인증에 성공하면 두 번째 생성자를 이용해 객체를 생성하여 Security Context에 저장

4. AuthenticationManager는 등록된 AuthenticationProvider을 조회하여 인증 요구

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

5. 실제 DB에서 사용자 인증 정보를 가져오는 UserDetailService에게 사용자 정보를 넘겨줌

 - UserDetailService는 UserDetails객체를 반환하는 하나의 메소드만을 가지고 있음
 - 일반적으로 이를 상속 받은 클래스에 UserRepository를 주입 받아 DB와 연결 처리

6. 넘겨 받은 사용자 정보를 통해 DB에서 찾은 사용자 정보인 UserDetails 객체를 만듦

 - 인증에 성공하여 생성된 UserDetails 객체는 Authentication 객체를 구현한 UsernamePasswordAuthenticationToken을 생성하기 위해 사용

7. AuthenticationProvider은 UserDetails를 넘겨받고 사용자 정보를 비교

8. 인증이 완료되면 권한 등의 사용자 정보를 담은 Authentication 객체 반환

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

9. 다시 최초의 AuthenticationFilter에 Authentication 객체 반환

10. Authentication 객체를 SecurityContext에 저장

 - Authentication 객체는 SecurityContext에 저장되며 SecurityContextHolder를 통해 SecurityContext에 접근하고 SecurityContext를 통해 Authentication에 접근 가능

 

 

반응형