How To Access Extra Fields From UserDetails In Spring Security

--

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 access id and fullName 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 definesgetPrincipal() method without considering a specific type in org.springframework.security.core.Authentication interface, you can access the CustomUserDetails object the way you normally access the User.

Thanks for reading!

Credits:

--

--

No responses yet