개발/TIL

[TIL#33] UserDetailsImpl의 생명 주기

서해쭈꾸미 2024. 6. 5. 22:52
오늘 공부 키워드

1. Spring Security custom AuthenticationFilter / AuthorizationFilter 구현

2. Spring Security 공부

 

 

UserDetailsImpl 생명주기

뉴스피드 팀 프로젝트 진행 중에 Spring Security custom AuthenticationFilter에서 유저 정보를 가져와야 하는 경우가 있었다. UserDetailsImpl 객체에서 유저 정보를 가져올 수 있어서 UserDetailsImpl를 사용해볼까 하는 생각이 들었다. 그러기 위해선 UserDetailsImpl가 언제 생성되고, 언제 소멸되는지 확인해볼 필요가 있다고 생각했다. 

 

 

생성 시점  

1. 사용자가 로그인 할 때 (인증)

2. JWT를 포함한 요청이 들어올 때 (인가)

 

소멸 시점 

인증 과정이 완료되면 Authentication 객체에 포함된 UserDetailsImpl 객체는 사라진다.

인가 과정에서는 요청이 완료되면 SercurityContext가 비워지면서 UserDetailsImpl객체도 소멸된다.

 

 

 

즉, 인증 과정에서는 인증이 완료될 때까지 UserDetailsImpl 객체가 유지되고, 인가 과정에서는 SecurityContext에 저장되어 요청이 처리되는 동안 유지된다. 요청이 완료되면 SecurityContext는 비워진다.

추가로 UserServiceImpl에서 UserDetails 객체를 만들어 반환하는 메서드를 구현한다면, UserServiceImpl을 통해 UserDetailsImpl 객체를 언제든 사용 가능하다.