How to integrate Spring Security with a custom database

RMAG news

To integrate Spring Security with a custom database, you can follow these steps:

Create a Custom UserDetailsService:

Implement the UserDetailsService interface to load user details from your custom database. This interface has a single method loadUserByUsername(String username) that returns a UserDetails object.

Override the loadUserByUsername method to query your database for the user details.

Configure Spring Security:

In your Spring Security configuration file (e.g., security.xml or security-config.xml), define the UserDetailsService bean.

Configure the AuthenticationManager to use your custom UserDetailsService.

Set Up Database Tables:

Create the necessary tables in your database to store user information. For example, you might need tables for users, roles, and authorities.

Use JDBC for Authentication:

Use Spring’s JdbcTemplate to interact with your database. You can define a DataSource bean and use it to query your database for user authentication.

Here is a step-by-step guide to integrate Spring Security with a custom database:

Step-by-Step Guide

Create a Custom UserDetailsService:

public class CustomUserDetailsService implements UserDetailsService {
private JdbcTemplate jdbcTemplate;

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Query your database for the user details
String query = “SELECT * FROM users WHERE username = ?”;
User user = jdbcTemplate.queryForObject(query, new Object[]{username}, new UserRowMapper());
if (user == null) {
throw new UsernameNotFoundException(“User not found”);
return user;


Configure Spring Security:


<http auto-config=”true”>
<intercept-url pattern=”/admin*” access=”ROLE_ADMIN”/>
<form-login login-page=”/login” default-target-url=”/welcome”
<logout logout-success-url=”/login?logout”/>

<authentication-provider user-service-ref=”customUserDetailsService”/>

<beans:bean id=”customUserDetailsService” class=”com.example.CustomUserDetailsService”/>


Set Up Database Tables:

Create tables for users, roles, and authorities in your database.

Use JDBC for Authentication:

public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
return dataSource;

public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);

Example Project Structure

Here is an example project structure to illustrate the integration:

├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ ├──
│ │ │ └──
│ │ └── resources/
│ │ ├──
│ │ ├── security.xml
│ │ └── web.xml
│ └── test/
│ └── java/
│ └── com/
│ └── example/
│ └──
└── pom.xml


By following these steps, you can integrate Spring Security with a custom database, allowing you to authenticate users using your own database schema and queries. This approach provides flexibility and customization for your authentication needs.