작성
·
58
0
실제로 UserDetails를 구현하고 있는 건
"AccountContext" 이지 "AccountDTO"가 아니기 때문에,
@AuthenticationPrincipal AccountDto accountDto를 하면 null이 반환될 수 있지 않나요?
그래서 차라리
@AuthenticationPrincipal AccountContext accountContext를 해서
if (accountContext != null) {
model.addAttribute("username", accountContext.getUsername());
} else {
model.addAttribute("username", "비회원");
}
이렇게 하는게 더욱 올바른 방법이 아닌가요?
답변 2
0
Principal 속성에 담긴 객체가 AccountContext 이면 @AuthenticationPrincipal AccountContext accountContext 로 하는게 맞습니다
Authentication 의 Principal 속성에 무엇을 저장했는지에 따라 @AuthenticationPrincipal 옆에 해당 타입을 선언하면 됩니다.
AccountContext 객체에 바로 사용자 정보를 담거나 혹은 AccountContext 객체에 AccountDto 객체를 담아서 사용자 정보를 편리하게 활용할 수 있습니다.
정답이 있는 것은 아닙니다.
0
안녕하세요, 인프런 AI 인턴입니다. 김민석님.
스프링 시큐리티에서 @AuthenticationPrincipal
을 사용할 때, 어떤 객체를 주입받는지는 Authentication
객체의 getPrincipal()
이 반환하는 타입에 따릅니다. 일반적으로, 이 Principal
객체는 UserDetails
를 구현한 클래스여야 합니다.
님의 질문처럼 @AuthenticationPrincipal AccountDto
를 사용했는데 null이 반환되는 경우, 이는 CustomAuthenticationProvider
에서 UsernamePasswordAuthenticationToken
을 생성할 때 AccountDto
가 아닌 다른 객체(예: AccountContext
)에 Principal
을 설정했기 때문일 수 있습니다.
따라서 코드에서 @AuthenticationPrincipal AccountContext accountContext
를 사용하는 것이 현재 설정에서는 올바른 접근일 가능성이 높습니다. AccountContext
가 직접 UserDetails
를 구현하고 있으며, 실제로 이 객체가 토큰을 통해 반환되고 있기 때문입니다.
관련하여 더 자세한 설명을 참고하실 수 있는 링크들을 아래에 포함합니다:
스프링 시큐리티의 @AuthenticationPrincipal 사용법
Principal
로 저장하는 객체에 대해 어떻게 결정할 수 있는지를 설명합니다.CustomAuthenticationProvider에서 principal 설정
CustomAuthenticationProvider
에서 왜 특정 객체를 선택하여 Principal
로 설정하는지를 다룹니다.저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.