On this page we will walk through the spring MVC security JDBC authentication example with custom UserDetailsService and database tables using java configuration. UserDetailsService provides a method loadUserByUsername() in which we pass username obtained from login page and it returns UserDetails. We need to override this method in a class which implements UserDetailsService. With the help of this custom UserDetailsService implementation, we are able to use custom table structure for our spring security authentication using JDBC. In our example, we are using a JDBC property file to get credentials and create DataSource bean in java configuration. We will create a DAO to access user information using JDBC and SQL queries. Find the complete example step by step.

Custom Database Tables for Spring Security Authentication

In our example we will use custom database tables. We can manage user, password and role according to our own way. Just for the example I am using two tables. Find the schema and data inserted into it. Password is in SHA-1 encoded.
Database Schema

DAO for JDBC Authentication

Find the DAO class which provides a method to return user information for the given username. While accessing user information we create SQL query for our custom tables. From the DAO class, UserDetailsService needs username, password and role for the given username and to provide these value, we are free to use any table structure , ORM or SQL queries.
UserDAO.java

Custom UserDetailsService | Override loadUserByUsername() Method

To use custom UserDetailsService, we will create a class and implement its method loadUserByUsername(String username) which returns UserDetails. In login page, we enter username and password, and while authentication, spring security calls this method passing username obtained from login page.
AuthenticationService.java

Java Configuration for Spring Security and UserDetailsService

In spring security java configuration, we are creating a bean for DataSource which will be used to connect to database. We are implementing a method configureGlobal() which has the argument AuthenticationManagerBuilder using which we call a method userDetailsService() to assign the instance of custom UserDetailsService. We are using SHA-1 password encoding for authentication.
SecurityConfig.java