How to use a custom UserDetailsService to save a DB User Entity in the Spring Security Authentication Object

When working with web applications most of the time we’ll want to store our User objects in a Database and use something like JPA annotations and spring data repositories to make life easier with our persistence.

Unfortunately Spring Security assumes it’s own User class which doesn’t necessarily have all the fields we might be interested in assigning to a User, such as email.

However, it is possible to marry your DB User Entity with your Spring Security User object so that it is available from Authentication objects.

Create a User Entity

First lets create a new User entity, for clarity I will omit any validation annotations.

Nice and simple, now lets create a UserRepository to interact with the DB

The building blocks are now in place to store and retrieve users from the DB.

Create a User Details Service

In order to use our DB User in the application we’re going to extend Spring’s User class and aggregate our DB user

In order to use our UserPrincipal we need a custom UserDetailsService which retrieves the user from the UserRepository

Wire the User Details Service in the Configuration

The last step is to configure this custom UserDetailsService in our Security Configuration WebSecurityConfigurerAdapter (unrelated configuration omitted below).

Access the User Entity from the Authentication Object

Now our DB user is loaded into the Authentication Manager at login and is available through Authentication objects in our controllers.

The logged in users email address can now be displayed in the view technology of your choice.

As usual please leave your opinion or any improvements you think can be made in the comments below!

2 thoughts on “How to use a custom UserDetailsService to save a DB User Entity in the Spring Security Authentication Object”

  1. I am getting:

    java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to com.core.entity.common.security.UserPrincipal

Leave a Reply

Your email address will not be published. Required fields are marked *