How To Access Extra Fields From UserDetails In Spring Security
Oct 27, 2024
Long story short, in order to access the extra fields you need, implement a custom UserDetails object that implements org.springframework.security.core.userdetails.UserDetails
interface.
- Create a new class called CustomUserDetails that implements
UserDetails
interface. In this class, you can define the extra properties you want to access that normally already exist in the user entity. In the context of this example, we’ll accessid
andfullName
fields.
- Create an implementation of
org.springframework.security.core.userdetails.UserDetailsService
interface to retrieve the user information from the database.
I’ll not go deeper into database or security filter related areas. Let's see how to access the id field from the new UserDetails implementation.
- .As Spring Security defines
getPrincipal()
method without considering a specific type inorg.springframework.security.core.Authentication
interface, you can access the CustomUserDetails object the way you normally access the User.
Thanks for reading!