Framework/Spring

[Spring Security] @AuthenticationPrincipal

비소_ 2022. 7. 11.

https://spring.io/guides/topicals/spring-security-architecture/

 

Spring Security Architecture

this topical is designed to be read and comprehended in under an hour, it provides broad coverage of a topic that is possibly nuanced or requires deeper understanding than you would get from a getting started guide

spring.io

공식문서를 참고하여 작성했습니다.

@AuthenticationPrincipal

@RequestMapping("/foo")
public String foo(@AuthenticationPrincipal User user) {
  ... // do stuff with user
}

해당 어노테이션은 주로 Controller단에서 인증된 사용자의 정보를 받아오기 위해서 사용하며,

Security Context에서 현재 Authentication 객체를 가져와 getPrincipal() 메서드를 호출합니다.

Principal은 인증 확인(validate)에 사용되는 AuthenticationManger에 따라 달라지므로, 사용자 데이터에 대한 type-safe reference를 얻는 작은 트릭이 될 수 있습니다.

SecurityContextHolder 구조

또한, Authentication 특성 상 UserDetailsService에서 반환된 데이터가 파라미터로 들어옵니다.

사용자 정보를 얻을 수 있는 또 다른 방법인 Principal(동명이의)은 getName() 메서드 밖에 활용하지 못하는 것에 비해

UserDetails를 통해 다양한 정보를 획득할 수도 있습니다.

(여기서 말하는 Principal은 Security 라이브러리에 있는 인터페이스를 의미합니다.)

public interface UserDetailsService {
	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

UserDetailsService는 추상 메서드 한개로 이루어져 있으며, DB에서 username을 찾아 UserDetails를 반환시킵니다.

따라서, UserDetails를 구현한 클래스에 이름, 이메일, 생일 등 다양한 정보를 정의해 놓았다면, 그 정보들을 getter를 통해 받아올 수 있는 것 입니다.

 

참고해도 좋은 블로그

https://ncucu.me/137

 

Spring Security - @AuthenticationPrincipal

Spring Security - @AuthenticationPrincipal @AuthenticationPrincipal 로그인한 사용자의 정보를 파라메터로 받고 싶을때 기존에는 다음과 같이 Principal 객체로 받아서 사용한다. 하지만 이 객체는 SecurityCo..

ncucu.me

 

댓글