일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- 창원에서 부산
- laravel
- ImageLoad
- spring boot
- android ImageLoad
- 안드로이드 이미지 로드
- android facebook
- 삼량진
- 자바
- 구포에서 자전거
- mysql
- 삼량진 자전거
- volley
- 로드바이크
- workbench
- android imageView zoom
- 구포에서 삼량진
- 부산에서 창원
- 부산에서 창원 자전거
- 자전거
- NetworkImageView
- c언어 구조체
- httpclient post
- spring
- C언어
- 구조체
- elk stack
- android loadImage
- 낙동강 종주
- image zoom
Archives
- Today
- Total
은근한
Spring boot 현재 세션 가져오기 본문
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 메소드들을 사용 할 수있게 되고 인증되어있는 즉, 세션의 정보를 가져 올 수 있다.
참조