로그인이 된 사용자 정보는 세션 안의 SecurityContext 에 보관된다.

이를 바로 꺼내 활용하는 방법이다.

 

이전에 만든 사용자 데이터를 가지고 있는 UserDetails의 구현체를 파라미터로 주입받아 사용한다.  

@GetMapping("/userInfo")
@ResponseBody
public String userInfo(@AuthenticationPrincipal CustomUserLogin customUser) {
    
    return customUser.getUsername();
}

 

@AuthenticationPrincipal : SecurityContext에 저장된 Authentication 객체의 principal 부분을 자동으로 캐스팅하여 주입,

별도의 복잡한 코드 없이 파라미터만으로 현재 로그인한 유저의 상세 객체를 불러올 수 있음.

 

+ Recent posts