Back-end/Spring-Security
- SecurityContext, SecurityContextHolder, Authentication간의 관계, 현재 로그인 중인 사용자 가져오기
prden
2021. 4. 3. 11:16
1. Authentication :
Authentication에는 사용자의 인증 여부(enabled), 사용자가 가진 권한(authority), 이름 및 접근 주체(username=principa)에 대한 정보를 담고 있다
- 관계 :
SecurityContextHolder class의 getContext() 메서드는 SecurityContext 객체를 리턴하고, 이 SecurityCotnext 객체의
getAuthentication() 메서드는 Authentication을 리턴함
따라서 현재 로그인한 사용자명을 획득하기 위해서는
//String username = SecurityContextHolder.getContext().getAuthentication().getName();
public CalendarUser getCurrentUser() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (authentication == null) {
return null;
}
User user = (User)authentication.getPrincipal();
String email = user.getUsername();
if (email == null) {
return null;
}
CalendarUser result = calendarService.findUserByEmail(email);
if (result == null) {
throw new IllegalStateException(
"Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
}
return result;
}
이처럼 구해올 수 있고 Authentication 객체 사용 시 사용자가 로그인하지 않은 경우, username값이 null이 되기 때문에 항상 null 체크를 해야 한다.
※ Spring Security의존제거, HttpServletRequest이용 이글을 참고하면 spring security API에 의존하지 않고 현재 로그인한 사용자 정보 꺼내올 수 있다. prde.tistory.com/33?category=938806
2. SpringSecurity 구조도
