Back to the Core

Let’s create a custom user-principal

A principal is a “corporation, a program thread, an individual, or anything that can have an identity”.

The user-principal implements a Spring Security Interface that is UserDetails. We prefer using the composition pattern rather than inheritance. In fact, if we decided to use inheritance, we would have had issues with the constructors, having to import all the required parameters so that the signatures of the methods match. It’s been deprecated as an approach in more recent versions. I did try that approach as well, and it was a no-go. Therefore, we prefer to inject the user into CustomUserPrincipal and, on class instantiation, we assign our user to the user attribute of our object.

If you have IntelliJ, you can just Command(Ctrl)+Click it and read info about UserDetails. The basic idea is that when we implement an interface, it is like a contract, and we need to honor it, which means we need to provide an implementation for its methods.

Get hands-on with 1200+ tech skills courses.