[Spring] Spring Security 로그인 사용자 정보 가져오는 방법

[Spring] Spring Security 로그인 사용자 정보 가져오는 방법

728x90

Spring Security에서 현재 로그인한 사용자의 정보를 가져오는 방법을 알아보도록 하자.

SecurityContextHolder 이용

Spring Security에서 전역으로 선언된 SecurityContextHolder를 통해서 정보를 가져올 수 있다.

SecurityContextHolder는 Spring Security Architechture에서 간단하게 알아본 적이 있는데

( https://joomn11.tistory.com/90 )

해당 클래스를 통해서 인증을 통해 발급된 Authentication을 얻을 수 있다.

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String userName = auth.getName();

Controller 메서드 인자 이용

Controller로 선언된 클래스의 메서드에서 인자로 Authentication 객체에 접근을 할 수 있다.

@Controller public class UserController { @GetMapping("/user") public String userName(Authentication authentication) { String userName = authentication.getName(); return userName; } }

추가적으로, Principal 객체도 얻을 수 있다.

@Controller public class UserController { @GetMapping("/user") public String userName(Principal principal) { String userName = principal.getName(); return userName; } }

728x90

from http://joomn11.tistory.com/91 by ccl(A) rewrite - 2021-12-01 21:01:39