[Spring Security] UserDetails V.S Authentication

minseok Kim·2025년 2월 16일

Spring Security

목록 보기
10/15

이번 포스트는 UserDetails과 Authentication의 차이점을 알아 보았다.

사용자 정보를 담는 객체로 Authentication과 UserDetails이 있는데, 둘의 차이는 무엇이고 왜 다른 객체로 나눠져 있는지 알아보았다.
위 그림은 Spring Security의 기본 인증과정을 나타낸 내부 flow이다.


UserDetails

먼저 UserDetails는 인터페이스이고, 이를 구현한 클래스들이 존재한다.
그 중 User라는 클래스를 보면 getPassword(), getUsername(), getAuthroties(), isAccountNonExpired(), isAccountNonLocked(), isEnabled(), isCredientialsNonExpired(), eraseCredentials() 등의 메서드가 존재한다.

UserDetails은 저장소(메모리, DB 등)에서 유저 정보를 load할 때 사용된다. UserDetails의 가장 큰 특징은 인증을 하는 과정에서 필요로 한다는 것이다.
isAccountNonExpired(), isAccountNonLocked(), isEnabled() 등의 메서드들은 인증을 하는 과정에서 해당 계정이 유효한지 등을 파악하는 기능들로, 인증이 이미 실패했다면 호출될 필요가 없는 메서드이다.

앞서 포스트에서 Authentication 객체는 인증 여부와 무관하게 사용자 정보로 채워지고, 실제 인증은 AuthenticationProvider가 진행한다 했는데, 실제 인증을 하는 과정(UserDetailsService, UserDetailsManager 등에서 실제 인증 진행)에서는 Authentication 대신 UserDetails이 사용된다.


Authentication

Authentication은 JDK에서 제공하는 Principal이라는 인터페이스를 extends하는 인터페이스이다.
Authentication의 구현 클래스로 UsernamePasswordAuthenticationToken과 같은 클래스 들이 있다.
Aututhentication에는 getName(), getPrincipal(), getAuthorities(), getCredentials(), getDetails(), isAuthenticated(), setAuthenticated(), eraseCredentials() 등이 있는데, isAuthenticated(), setAuthenticated()을 제외하면 UserDetails에서 제공하는 메서드들과 유사해 보이는 것을 확인할 수 있다.

isAuthenticated(), setAuthenticated()이 Authentication과 UserDetails의 가장 큰 차이점으로, Authentication은 인증이 실패했는지, 성공했는지 여부를 필요한 경우 사용된다.
Authentication 객체는 AuthenticationProvider, AuthenticationManager등에서 사용되고, 실제 인증 과정이 아닌 해당 유저 정보의 인증이 성공했는지, 실패했는지에 대한 인증 결과를 담는 역할을 하는 것이 UserDetails과의 가장 큰 차이점이다.

정리를 해보면, UserDetails은 유저 정보를 실제 인증할 때, Authentication은 유저가 인증을 성공했는지, 실패했는지 여부를 나타낼 때 사용한다고 할 수 있겠다.

최종 인증 여부는 Authentication에서 확인할 수 있으므로, 아래 다이어그램처럼 UserDetailsService, UserDetailsManager에서 UserDetails을 통해 인증 과정을 진행하고,
AuthenticationProvider에서 UserDetails을 Authentication으로 바꿔 인증 결과를 포함하도록 한다.

0개의 댓글