Search code examples
javaspringjakarta-eespring-securityspring-security-rest

Spring Security user authentication against customers and employee


I am new to Spring Security. I have a Spring Boot application with two different types of entities. Customers and employees. In Employees I have normal employees, admins and super users. Since I am using JPA, each entity has its own repository. How to model my UserDetailsService with loadUserByUsername since this is a common method to validate against many repositories. Is there anything that I am missing to model around my entities?

Additional Info:

In my design, I have two entities. Customer and Employee. Employee will have roles like NORMAL, ADMIN and SUPER_USER. Customer is a different entity.

Will there be two UserDetailsService and two AuthenticationProvider each pointing to its own table (Customer and Employee)?


Solution

  • As your requirement is to have multiple authentication entry points it is not as simple as Atul's answer.

    What you need is

    1. You need to differentiate customer and employee while logging in. (Preferred way radio button)

    2. You need to implement your custom authentication filter i.e, implementation of UsernamePasswordAuthenticationFilter instead of spring-security provided default .formLogin()

    3. Create two UsernamePasswordAuthenticationToken as EmployeeUsernamePasswordAuthenticationToken and CustomerUsernamePasswordAuthenticationToken

    4. In your custom filter get userType from request and based on userType set authToken as empAuthToken or customerAuthToken to differentiate required authentication provider.

    5. Create AuthenticationProvider as EmployeeCustomAuthenticationProvider and CustomerCustomAuthenticationProvider where each AuthenticationProvider should be overridden supports method where AuthenticationProvider supports specific token either customerAuthToken or employeeAuthToken.

    6. Override authenticate method where authenticate method has been passed with Authentication parameter from which you can get both username and password which you can pass to any of you custom service to authenticate user and grant authorities required for user.

    While implementing your CustomAuthenticationFilter it is also required to provide your custom authenticationSuccessHandler and AuthenticationFailureHandlers.

    If you implement all above without any mistake you can avoid fallback authentication which spring-security provides by default if two customAuthenticationProviders are configured.

    For more detail of implementing multiple authentication entry point using java configuration refer my answer given below Multiple AuthenticationProvider with different UsernamePasswordAuthToken to authenticate different login forms without fallback authentication

    and also you can download working code from my github repository