Framework & Library/Spring

[Java / Spring] Spring Security 로그인 정보 가져오기 @AuthenticationPrincipal

마볼링 2022. 12. 29. 07:05

로그인한 사용자의 정보를 파라미터로 받아오고 싶을 때, Java 표준 Principal 객체를 받아서 사용한다.

하지만, Java 표준 Principal 객체는 name 정보만 참조할 수 있다.

 

@AuthenticationPrincipal 어노테이션을 사용하면 UserDetailsService에서 Return한 객체를 파라미터로 직접 받아 사용할 수 있다.

인스타그램 클론코딩에서 UserDetailsService 인터페이스를 상속받아 구현체를 만들었다.

@RequiredArgsConstructor
@Service
public class PrincipalDetailsService implements UserDetailsService {

   private final UserRepository userRepository;

   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      User userEntity = userRepository.findByUsername(username);
      if(userEntity == null) {
         return null;
      } else {
         return new PrincipalDetails(userEntity);
      }
   }
}

 여기서 리턴된 객체를 PrincipalDetails 객체이다.

PrincipalDetails객체 또한 UserDetails 인터페이스를 상속받은 구현체이다.

@Data
public class PrincipalDetails implements UserDetails {

   private User user;

   public PrincipalDetails(User user) {
      this.user = user;
   }

   @Override
   public Collection<? extends GrantedAuthority> getAuthorities() {
      Collection<GrantedAuthority> collection = new ArrayList<>();
      collection.add(new GrantedAuthority() {
         @Override
         public String getAuthority() {
            return user.getRole();
         }
      });
      return collection;
   }

   @Override
   public String getPassword() {
      return user.getPassword();
   }

   @Override
   public String getUsername() {
      return user.getUsername();
   }

   @Override
   public boolean isAccountNonExpired() {
      return true;
   }

   @Override
   public boolean isAccountNonLocked() {
      return true;
   }

   @Override
   public boolean isCredentialsNonExpired() {
      return true;
   }

   @Override
   public boolean isEnabled() {
      return true;
   }
}

이제 컨트롤러에서 @AuthenticationPrincipal 어노테이션을 사용하고 PrincipalDetails 객체를 받으면

로그인된 세션 정보를 받을 수 있다.

@GetMapping("/user/{id}/update")
public String update(@PathVariable int id, @AuthenticationPrincipal PrincipalDetails principalDetails) {
   log.info(principalDetails.toString());
   return "user/update";
}

결과

com.GStagram.web.UserController          : PrincipalDetails(user=User(id=1, username=qwe2487, password=$2a$10$/LeByXsjkdR4lVcOjREOe.Z30YQJ5suGw0ilrQb6LW1dgCEP1PjtG, name=이민혁, website=null, bio=null, email=repeater2487@naver.com, phone=null, gender=null, profileImageUrl=null, role=ROLE_USER, createDate=2022-12-29T07:03:58.430718))