Spring Security - JDBC Authentication

Last Updated : 3 Jun, 2026

Spring Security JDBC Authentication is a mechanism in which user credentials (username and password) and roles/authorities are stored in a relational database. During login, Spring Security uses JDBC to query the database, validate user credentials, and determine user permissions.

  • User credentials are stored in a relational database.
  • Spring Security authenticates users using JDBC queries.
  • Supports authentication and authorization.

Importance of JDBC Authentication

JDBC Authentication is important because it stores user credentials and roles in a database instead of hardcoding them in the application. This makes user management easier, more secure, and suitable for real-world applications.

  • Centralized User Management – All user accounts and roles are stored in a single database.
  • Persistent Storage – User data remains available even after the server restarts.
  • Scalability – Can handle a large number of users efficiently.
  • Enhanced Security – Supports encrypted passwords and secure authentication mechanisms.
  • Easy User Updates – Users, passwords, and roles can be modified directly in the database without changing application code.
  • Production Ready – Widely used in enterprise and real-world applications.

Example: Spring Security JDBC Authentication in a Spring MVC Web Project

Step 1: Create a Spring MVC Project

Create a Dynamic Web Project in STS and configure Apache Tomcat.

  • STS 4 IDE
  • Apache Tomcat Server
  • Maven Project
  • Java
  • MySQL Database

Step 2: Database Setup

Create a database and tables in MySQL:

Java
CREATE DATABASE gfgspringsecuritydemo;

USE gfgspringsecuritydemo;

CREATE TABLE users (
    username VARCHAR(50) NOT NULL PRIMARY KEY,
    password VARCHAR(100) NOT NULL,
    enabled BOOLEAN NOT NULL
);

CREATE TABLE authorities (
    username VARCHAR(50) NOT NULL,
    authority VARCHAR(50) NOT NULL,
    CONSTRAINT fk_user FOREIGN KEY(username) REFERENCES users(username)
);

Insert some test users:

Java
INSERT INTO users (username, password, enabled)
VALUES ('ami', '123', true),
       ('biki', '456', true);

INSERT INTO authorities (username, authority)
VALUES ('ami', 'ADMIN'),
       ('ami', 'ADMIN'),
       ('biki', 'USER');

JDBC-Authentication-2.png

JDBC-Authentication-3.png

Step 3: Project Folder Structure

Your project structure should look like this:

Lightbox

Step 4: Add Dependencies in pom.xml

Add the following dependencies to your pom.xml file

  • Spring Web MVC
  • Java Servlet API
  • Spring Security Config
  • Spring Security Web
  • Spring JDBC
  • MySQL Connector Java

pom.xml:

Java
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="https://maven.apache.org/POM/4.0.0"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gfg.springsecurity</groupId>
    <artifactId>springsecurity</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springsecurity Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.gfg.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.24</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.7.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.7.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.24</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>springsecurity</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven 
                defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see https://maven.apache.org/ref/3.9.11/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

Step 5: Configure Dispatcher Servlet

Go to the src > main > java and create a class WebAppInitilizer. DispatcherServlet acts as the Front Controller and handles all incoming HTTP requests.

WebAppInitilizer.java

Java
package com.gfg.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitilizer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MyAppConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

Step 6: Configure Spring MVC

Create another class in the same location (src > main > java) and name it MyAppConfig.

MyAppConfig.java

Java
package com.gfg.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com")
public class MyAppConfig {

    @Bean
    InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

Step 7: Create Controller

Go to the src > main > java and create a class GfgController. This controller handles requests to /gfg.

GfgController.java

Java
package com.gfg.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class GfgController {

    @GetMapping("/gfg")
    public String helloGfg() {
        return "hello-gfg";
    }
}

Step 8: Create View

Go to the src > main > webapp > WEB-INF > right-click > New > Folder and name the folder as views. Then views > right-click > New > JSP File and name your first view.

hello-gfg.jsp

Java
<!DOCTYPE html>
<html>
<body bgcolor="green">
    <h1>Hello GeeksforGeeks!</h1>
</body>
</html>

Step 9: Configure JDBC Authentication

Go to the src > main > java and create a class MySecurityAppConfig and annotate the class with @EnableWebSecurity annotation. This class will help to create the spring security filter chain.

MySecurityAppConfig.java

Java
package com.gfg.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

@SuppressWarnings("deprecation")
@EnableWebSecurity
public class MySecurityAppConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource datasource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
            .dataSource(datasource)
            .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}

Step 10: Register Security Filter

Go to the src > main > java and create a class SecurityInitializer. This class will help to register the spring security filter chain with our application.

Java
package com.gfg.config;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}

Step 11: Configure DataSource

Update MyAppConfig.java to include a DataSource bean:

Java
@Bean
DataSource dataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setUrl("jdbc:mysql://localhost:3306/gfgspringsecuritydemo");
    ds.setUsername("root");
    ds.setPassword("your_password_here");
    ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
    return ds;
}

Step 12: Run the Application

  • Right-click project -> Run As -> Run on Server.
  • Open browser:

http://localhost:8080/springsecurity/gfg

And it will ask for authentication to use the endpoint and a pop-up screen will be shown like this.

Now sign in with your database credentials

  • Username: ami
  • Password: 123

Note: For learning purposes, plain-text passwords are used; in real applications, passwords must be encrypted using a PasswordEncoder.

And now you can access your endpoint.

Comment