함께 성장하는 기록장

꾸준한 기록이 모여 도서관이 될 수 있도록

Spring

Spring Security 알아보기 - 개념, 과정

H-jinny 2024. 7. 4. 21:55

Spring Security

Spring을 통해 어플리케이션을 만들다보면 로그인 기능을 사용할 때가 있다. 이런 보안과 관련한 기능들을 직접 구현하기에는 어려움이 많은데, Spring Security가 제공하는 보안과 관련한 기능(인증, 인가 등)을 이용하면 개발자는 보안관련 로직을 직접 작성하지 않고 서비스 로직에 집중할 수 있다. 즉 Spring Security는 인증(Authentication)과 인가(Authorization)에 대한 처리를 위임하는 프레임워크이다. 

 

우선 어떻게 동작하는지 알아보면 좀 더 와닿을 것 같고, 이해가 잘 된 것 같아 흐름을 정리하려고 한다.

 

 

Spring Security 아키텍처

Spring Security는 인증과 권한에 대한 부분을 Filter 흐름에 따라 처리한다. 이 Filter는 Dispatcher Servlet 보다 먼저 적용되므로 가장 먼저 URL 요청을 받는다.

* 이전에 작성한 Spring MVC 구조에서 Dispatcher Servlet을 확인할 수 있다.

 

www.springbootdev.com - Chathuranga Tennakoon 참고

 

1. 사용자가 로그인 정보(아이디, 비밀번호)를 입력 후 인증 요청

2. AuthenticationFilter에서 (1)의 요청을 가로채어 아이디와 비밀번호를 기반으로 UsernamePasswordAuthentication Token 생성(Authentication 객체)

3. (2)의 정보를 AuthenticationManger(구현체인 AuthenticationProvider에서 사용하게 됨 - 4)로 전달

4. AuthenticationManager는 전달받은 토큰을 순차적으로 AuthenticationProvider들에게 전달하여 실제 인증 과정수행

5. AuthenticationProvider는 UserDetailsService로 조회할 (3)의 사용자 정보 전달

6. (3)의 아이디를 기반으로 DB에서 데이터를 조회(아이디, 비밀번호가 일치하는지 확인)

7. 조회 결과 반환(성공 시 AuthenticationSuccessHandle, 실패 시 AuthenticationFailureHandle 실행)

8. 인증 처리 후 토큰을 AuthenticationManager에 반환하면 AuthenticationProvider에서 UserDetailsService를 통해 조회한 정보와 입력받은 비밀번호가 일치하는지 확인. 일치하는 경우 인증된 토큰을 반환

9.  AuthenticationManager는 인증 완료된 Authentication 객체를 AuthenticationFilter로 전달

10. AuthenticationFilter는 LoginSuccessHandler로 전달. 인증된 토큰을 SecurityContextHolder에 저장

 

 

 

Spring Security 구성

위의 흐름에 추가하여, 구성 요소들이 어떤 기능을 하는지 다음과 같이 정리할 수 있을 것이다.

 

SecurityContextHolder

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

SecurityContextHolder를 통해 SecurityContext에 접근

 

SecurityContext

Authentication을 보관하는 역할

SecurityContext를 통해 Authentication에 접근할 수 있음

 

Authentication

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

Authentication 객체는 SecurityContext에 저장됨

 

AuthenticationManager

인증에 대한 부분을 처리

실질적으로 AuthenticationManager에 등록된 AuthenticationProvider에 의해 처리됨

인증이 성공하면 인증이 성공한 객체를 생성하여 SecurityContext에 저장(세션을 사용할 경우 인증 상태를 유지하기 위해 세션에 보관)

 

AuthenticationProvider

실제 인증에 대해 처리하는 부분

인증 전의 Authentication 객체를 받아 인증 완료된 객체로 반환

AuthenticationProvider 인터페이스를 구현해서 Custom 한 AuthenticationProvider를 작성하여 AuthenticationManager에 등록하여 사용

 

PasswordEncoding

암호화에 사용될 PasswordEncoder 구현체를 지정

AuthenticationMangerBuilder.userDetailService().passwordEncoder()를 통해 지정

 

GrantedAuthority

사용자가 가지고 있는권한이 있는지 검사 및 접근 허용 여부 결정

 

 

 

 

 

Spring Security의 Filter 기반의 동작에 대해서는 다음 포스팅에서 다룰 예정이다.

 

 

 

참고

Spring Security (1) (velog.io)

Spring Security 가이드 (with. Spring boot 3.0) - 스프링 시큐리티란, 동작 과정, 사용 방법, JWT 발급 (tistory.com)

스프링부트 3.X 스프링 시큐리티 사용해서 회원가입, 로그인, 로그아웃 구현하기 — 동동이개발바닥 (tistory.com)
https://seungh1024.tistory.com/61

 

 

 

오타, 지적 감사합니다 :)

'Spring' 카테고리의 다른 글

Spring이란?  (0) 2024.09.02
Spring MVC 구조와 레이어드 아키텍처  (0) 2024.07.09
Maven vs Gradle  (0) 2024.07.04