Search code examples
springauthenticationspring-securitydatamodel

spring security datamodel


I'm currently using the spring-security libraries and I asked myself the following question: How should I combine my database model with the spring-security tables?

As you know spring-security needs two tables (users and authorities) to define an authentication manager in the database. From my pov there are now two possibilities where I store my additional user-information (like email, lastname, last-logged-on, ....)

  1. I could have a plain user-table for authentication purposes and another one for the rest (linked by the username)

  2. I extend the user-table of spring-security with my necessary attributes.

What is the best design from your perspective? What are your experiences?

Lomu


Solution

  • I created a POJO User which represents the User entity as conceived by the Spring Security library, and secondly I created a POJO ProfiledUser to represent a specialized type of user of my application. It is called ProfiledUser because I needed a user associated to a profile. Of course, a similar approach can be applyied for every type of user you need to represent. Basically, if you need more than one type of user you can make your classes to extend the User POJO. In the following you find the class, with the JPA annotations.

    @Entity
    @Table(name="USERS")
    @Inheritance(strategy=InheritanceType.JOINED)
    public class User implements UserDetails {
    
        private static final long serialVersionUID = 1L;
        private long id;
        private String username;
        private String password;
        private boolean enabled = true;
        Set<Authority> authorities = new HashSet<Authority>();  
        //...getters & setters
        }
    
    @Entity
    @Table(name="PROFILED_USERS")
    public class ProfiledUser extends User{
    
        private static final long serialVersionUID = 1L;
        //some custom attributes
        private PersonalData personalData;
        private ContactData contactData;
        private AddressData addressData;
        //...getters & setters
    
        }
    

    If you need to represent only one type of user, I think it should work to add attributes to the User class. However, I prefer to separate the abstract concept of user defined by the Spring Security framework from my business logic. So I'd recommend to implement your own SomethingUser and extend the User class.