Using Java 8 Optional to set Current User ModelAttribute in Spring Security

This post will be a bit of a follow on from that last one which discussed using a User entity from a database in Spring Security Authentication Object, so it’s probably worth reading that first.

The new Optional  class in Java 8 lets us create a neat little mechanism for transferring our User entity, if one exists, into every controller method, using a ControllerAdvice  along the way.

Starting with the UserPrincipal  class from the last post we’ll make the following modification:

Continue reading “Using Java 8 Optional to set Current User ModelAttribute in Spring Security”

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.

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