웹개발/SpringBoot

[Spring Security] @AuthenticationPrincipal를 이용하여 로그인한 사용자 알아내기

뎁쭌 2024. 4. 23. 19:44
728x90
반응형

Spring Security웹 애플리케이션의 인증과 인가를 담당하는 강력한 프레임워크이다. 이번 글에서는 Spring Security에서 제공하는 @AuthenticationPrincipal 어노테이션을 사용하여 로그인한 사용자의 정보를 쉽게 가져오는 방법에 대해 알아보자.

 

Authentication

최근에 Spring Boot와 Spring Security를 사용하여 웹 애플리케이션을 개발하던 중, 로그인한 사용자의 정보를 컨트롤러에서 사용해야 하는 상황에 직면했다. 처음에는 Authentication 객체를 직접 주입받아 사용하는 방법을 시도했다.
(게시글에 좋아요 기능 추가)

@PostMapping("/like")
public ResponseEntity<Void> likePost(@PathVariable Long postId, Authentication authentication) {
    CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
    UserAccount userAccount = userDetails.getUserAccount();
    // ...
}


위의 코드처럼 Authentication 객체를 주입받고, getPrincipal() 메서드를 호출하여 UserDetails 객체를 가져온 후 캐스팅하여 사용했다. 그러나 이 방법은 코드의 가독성이 좋지 않고, 매번 캐스팅해야 하는 번거로움이 있었다.

그러던 중 @AuthenticationPrincipal 어노테이션을 알게 되었고, 이를 사용하여 코드를 개선할 수 있다.

 

@AuthenticationPrincipal

@PostMapping("/like")
public ResponseEntity<Void> likePost(@PathVariable Long postId, @AuthenticationPrincipal CustomUserDetails userDetails) {
    UserAccount userAccount = userDetails.getUserAccount();
    // ...
}


@AuthenticationPrincipal 어노테이션을 사용하면 Spring Security가 인증된 사용자의 UserDetails 객체를 직접 주입해준다. 이를 통해 캐스팅 없이 바로 CustomUserDetails 객체를 사용할 수 있게 되었다.

하지만 @AuthenticationPrincipal을 사용할 때 주의할 점이 있다. CustomUserDetails 클래스가 UserDetails 인터페이스를 구현하고 있어야 한다. 그렇지 않으면 에러가 발생할 수 있다.

public class CustomUserDetails implements UserDetails {
    private UserAccount userAccount;
    
    // 생성자, 게터, 세터 등 필요한 코드 작성
    
    // UserDetails 인터페이스의 메서드들을 구현
    // ...
}


CustomUserDetails 클래스에서 UserDetails 인터페이스의 메서드들을 적절히 구현해야 한다. 이를 통해 Spring Security가 인증된 사용자의 정보를 CustomUserDetails 객체로 제공할 수 있다.

@AuthenticationPrincipal을 사용하면 코드의 가독성과 유지보수성이 향상되며, Spring Security의 기본 메커니즘을 활용할 수 있다. 로그인한 사용자의 정보가 필요한 곳에서 @AuthenticationPrincipal을 사용하여 간편하게 가져올 수 있다.

물론 @AuthenticationPrincipal을 사용할 때 에러가 발생한다면, `Authentication` 객체를 사용하는 방법으로 대체할 수도 있다. 하지만 가능하다면 @AuthenticationPrincipal을 사용하는 것이 좋다.

이상으로 @AuthenticationPrincipal 어노테이션을 사용하여 로그인한 사용자의 정보를 가져오는 방법에 대해 알아보았다. 이 방법을 활용하여 Spring Security와 함께 웹 애플리케이션을 개발할 때 로그인한 사용자의 정보를 쉽게 다룰 수 있다.