관리 메뉴

제뉴어리의 모든것

Spring Boot 현재 세션 가져오기 본문

Spring Boot

Spring Boot 현재 세션 가져오기

제뉴어리맨 2021. 3. 10. 13:25

Spring에서 인터셉터나 필터, 컨트롤러 등에서 로그인한 사용자 정보를 가져 오고 싶을 때

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

 

SecurityContextHolder.getContext().getAuthentication().getPrincipal() 와 같이 사용하여 필요한 데이터를 가져오면 된다.

그리고 getPrincipal()로 가져온 객체에서 로그인 유저의 데이터를 가져다가 쓰면 된다. (데이터 구조를 브레이크 포인트를 찍어서 확인해볼것..)

 

  • Get the username of the logged in user: getPrincipal()
  • Get the password of the authenticated user: getCredentials()
  • Get the assigned roles of the authenticated user: getAuthorities()
  • Get further details of the authenticated user: getDetails()

 

 

 

 

> Spring Security로 인증을 한 유저를 SecurityContextHolder.getContext().getAuthentication().getPrincipal() 써서 Object를 가져왔을때

Spring Security로 인증을 한 유저는 UserDetails 을 implements하고

구현한 객체를 반환한다. (UserDetailsService를 implements 한 구현 service 객체의

loadUserByUsername 함수가 리턴하는 객체)

 

getPrincipal() 해서 가져온 object의 데이터형

 

UserDetailsService 구현체
UserDetails의 구현체

Member는 UserDetails를 구현 했으므로 loadUserByUsername에서 리턴 가능하다.

 

 

 

> Oauth2로 인증을 한 유저를 SecurityContextHolder.getContext().getAuthentication().getPrincipal() 써서 Object를 가져왔을때 (네이버 로그인)

DefaultOAuth2User 데이터형의 변수를 반환한다. 

(OAuth2UserService<OAuth2UserRequest, OAuth2User> 를 implements 한 구현체의 loadUser 함수가 리턴하는 데이터형) 테스트 해보진 않았지만 아마도 OAuth2User 를 구현해 주면 직접 엔티티를 만들어서 핸들링 가능할듯 하다.

 

getPrincipal() 해서 가져온 object의 데이터형

 

 

OAuth2UserService<OAuth2UserRequest, OAuth2User> 구현체

 

 

 

참조 : Spring boot 현재 세션 가져오기 (tistory.com)