은근한

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

카테고리 없음

Spring boot 현재 세션 가져오기

EsJoo 2017. 9. 3. 03:16

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

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


  • 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()

4가지의 메소드가 있고, 유저이름을 알기위해서 getPrincipal() 메소드를 사용하는데

현재 문제점이 기본으로 스프링에서 제공하는 Authentication 방식과 다르게 커스텀이 되어있다.

디비에서 값을 불러오는 것과 세션, auth 등을 설정하다보니 커스텀이 되어 있고 이를 해결하는데에 하루정도 걸렸다...

해결한 방법은 커스텀한 클래스를 캐스트했다.

User principal = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof User) {
String name = principal.getEmail();
logger.info(name);
} else {
String name = principal.toString();
logger.info(name);
}

위에서 사용한 User는 UserDetails 상속하고있고 타입 몇개를 추가 했다.


public class User implements UserDetails{

private String id;
private String email;
private String password;
private String name;
private boolean isAccountNonExpired;
private boolean isAccountNonLocked;
private boolean isCredentialsNonExpired;
private boolean isEnabled;
private Collection<? extends GrantedAuthority> authorities;

...

유저로 캐스트해서 값을 가져오면 User클래스 내의 get/set 메소드들을 사용 할 수있게 되고 인증되어있는 즉, 세션의 정보를 가져 올 수 있다.





참조

https://stackoverflow.com/questions/31159075/how-to-find-out-the-currently-logged-in-user-in-spring-boot