Spring Security Custom Database Authentication

 

In this example, we will see how to create a custom database authentication provider to perform the authentication process.

We will use the Spring Security Custom Authentication example and enhance it to make the UserDetailsService using a database to retrieve the user data.

 

1. Technologies used

  • Spring Security 3.2.5.RELEASE
  • JSF 2.2.8
  • MySQL 5
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7
  • Tomcat 7.0

 

2. Project structure

We create a JSF 2 web application.

SpringSecurityCustomDatabaseAuthentication-0

 

3. Project dependencies

 

4. Create database tables

users: it contains the user credentials.

 

user_roles: it contains the user authorities

 

Create a user :

 

5. Create a custom authentication provider

First, create an implementation of GrantedAuthority interface.

That represents an authority granted to an authenticated user.

GrantedAuthorityImpl

 

Then, create an implementation of UserDetails interface to store user information : username, password and authorities.

UserDetailsImpl

 

And Finally,  create an implementation of UserDetailsService interface to retrieve user and his authorities based on the username.

In this example, the user data is stored in the users and user_roles tables

UserDetailsServiceImpl

 

UserDetailsServiceImpl uses UserDAO to get user entity and authorities.

UserDAO

 

6. Spring Security configuration

Indicate to Spring Security to use our implementation class as user authentication provider.

File : spring-security.xml :

 

7. Test It

URL : http://localhost:8080/SpringSecurityCustomAuthentication/login.jsf

SpringSecurityCustomDatabaseAuthentication

 

Bad authentication :

SpringSecurityCustomDatabaseAuthentication-2

 

Good authentication :

SpringSecurityCustomDatabaseAuthentication-1

Download source code