Home » Enterprise Java » spring » Security » Spring Security via Database Authentication Tutorial

About Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Spring Security via Database Authentication Tutorial

Welcome readers, in spring, the security module is considered important. It enables the developers to integrate the security features in a managed way. In this tutorial, we will explore how to design a custom login form and perform the user’s authentication using a database in the spring security.


1. Introduction

Model-View-Controller (MVC) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:

  • Model (M): Model’s responsibility is to manage the application’s data, business logic, and business rules. It is a POJO class which encapsulates the application data given by the controller
  • View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the JSP templates written with Java Standard Tag Library (JSTL)
  • Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet
Spring Security via Database Authentication - mvc overview
Fig. 1: Model-view-controller (mvc) overview

1.1 Spring Mvc Architecture and Flow

The main component of the spring mvc framework is the Dispatcher Servlet. Refer below diagram to understand the Spring MVC architecture.

Spring Security via Database Authentication - Architecture diagram
Fig. 2: Architecture diagram

In spring mvc framework Dispatcher Servlet access the front controller which handles all the incoming requests and queues them for forwarding to the different controllers.

  • Dispatcher Servlet is configured in the web.xml of the application and all the requests mapped to this servlet will be handled by this servlet. Dispatcher Servlet delegates the request to the controller (i.e. class annotated with the @Controller annotation)
  • The Controller class invokes the appropriate handler method based on the @RequestMapping annotation. This method returns the logical name of the View and the Model
  • Dispatcher Servlets resolves the actual view name using the ViewResolver (configured in the Spring Beans configuration file) and gets the actual view name
  • Passes the model object to the view so can be used by a view to display the result to the user

1.2 Spring Security

According to the Spring Security Project, Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. It allows developers to integrate the security features with J2EE web applications easily, and it takes care of all the incoming HTTP requests via Servlet Filters and implements the “user-defined” security checking.

Spring Security can be integrated with Servlet API and Spring Web MVC seamlessly. This feature of Spring Security when integrated with Spring MVC provides default login and log-out functionalities and an easy configuration for authentication and authorization.

Now, open up the Eclipse IDE and let us see how to implement this tutorial in the spring mvc framework.

2. Spring Security via Database Authentication Tutorial

Here is a systematic guide for implementing this tutorial in the spring mvc framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Spring Security via Database Authentication - Project Structure
Fig. 3: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Security via Database Authentication - Maven Project
Fig. 4: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

Spring Security via Database Authentication - Project Details
Fig. 5: Project Details

Select the Maven Web App archetype from the list of options and click next.

Spring Security via Database Authentication - Archetype Selection
Fig. 6: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring Security via Database Authentication - Archetype Parameters
Fig. 7: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:


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

We can start adding the dependencies that developers want like servlet api, mysql connector, spring mvc, and security framework. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the mysql connector, spring mvc, and security framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code.


<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<name>Springsecuritywithdatabase Maven Webapp</name>
		<!-- Servlet API Dependency -->
		<!-- Spring Framework Dependencies -->
		<!-- Spring Security Dependencies -->
		<!-- Spring JDBC dependency -->
		<!-- Mysql connector dependency -->
		<!-- JSTL Dependency -->

3.2 Database and Table Creation

The following script creates a database called springsecuritydb with tables: USERS and USERS_ROLES. Open MySQL terminal or workbench to execute this sql script.

SQL script

----- Create database from the application. -----

USE springsecuritydb;

----- User credentials table. -----
	user_id INT(50) NOT NULL,
	user_name VARCHAR(100) NOT NULL,
	password VARCHAR(50) NOT NULL,
	enabled boolean,
	PRIMARY KEY(user_id)

----- User roles/authorities table. -----
  user_role_id INT(50) NOT NULL,
  user_id INT(50) NOT NULL,
  authority VARCHAR(50) NOT NULL,
  PRIMARY KEY (user_role_id),
  FOREIGN KEY (user_id) REFERENCES users (user_id)

----- Sample users and their respective roles. -----
INSERT INTO users (user_id, user_name, password, enabled) VALUES (1, 'john', 'john123', true);
INSERT INTO users (user_id, user_name, password, enabled) VALUES (2, 'natalie', 'nat123', true);
INSERT INTO users (user_id, user_name, password, enabled) VALUES (3, 'tom', 'tom123', true);
INSERT INTO users_roles (user_role_id, user_id, authority) VALUES (1, 1, 'ROLE_ADMIN');
INSERT INTO users_roles (user_role_id, user_id, authority) VALUES (2, 2, 'ROLE_ADMIN');
INSERT INTO users_roles (user_role_id, user_id, authority) VALUES (3, 3, 'ROLE_ADMIN');

----- Displaying users and users_roles table data. -----
SELECT * FROM users;

If everything goes well, the database and the tables will be created.

Spring Security via Database Authentication - Database and Table creation
Fig. 8: Database and Table creation

3.3 Configuration Files

Let us write all the configuration files involved in this application.

3.3.1 Web deployment descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests and developers will also configure how spring mvc and security will be loaded during the application startup. The responsibility of the spring security filter will be to intercept the url patterns in order to apply the authentication and authorization as configured in the spring security configuration file. Add the following code to it.


<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<display-name>Spring security with database example</display-name>

	<!-- spring configuration - process the application requests -->


	<!-- spring security configuration -->

3.3.2 Spring configuration file

To configure the mvc framework, developers need to implement the bean configuration file which acts as an interface between the java class and the outside work. Put this file in the Springsecuritywithdatabase/src/main/webapp/WEB-INF/ folder and add the following code to it.


<?xml version="1.0" encoding="UTF-8"?>
    <context:component-scan base-package="com.spring.mvc.security.ctrl" />
    <!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources in the /WEB-INF/ Folder -->
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />

3.3.3 Spring security file

To configure the security framework, we will implement the security configuration file to support the authentication and authorization in the spring mvc. Put this file in the Springsecuritywithdatabase/src/main/webapp/WEB-INF/ folder and add the following code to it.


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

	<!-- spring security configuration -->
	<http auto-config="true">
		<intercept-url pattern="/admin**"
			access="hasRole('ROLE_ADMIN')" />

		<!-- user-defined login form redirection -->
		<form-login login-page="/login" default-target-url="/"
			authentication-failure-url="/login?error" />

		<!-- logout url -->
		<logout logout-success-url="/login?logout" />

		<!-- csrf disabled -->
		<csrf disabled="true" />

	<!-- spring authentication configuration via database -->
			<jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="select user_name, password, enabled from USERS where user_name = ?"
				authorities-by-username-query="select u.user_name, ur.authority from USERS u, USERS_ROLES ur where u.user_id = ur.user_id and u.user_name = ?" />

	<!-- database configuration (database = MySql) -->
	<beans:bean id="dataSource"
		<beans:property name="driverClassName"
			value="com.mysql.cj.jdbc.Driver" />
		<beans:property name="url"
			value="jdbc:mysql://localhost:3306/springsecuritydb" />
		<beans:property name="username" value="root" />
		<beans:property name="password" value="" />

3.4 Controller Class

Let us write the controller class involved in this application. The controller is designed to handle the request for the secure page. Add the following code it.


package com.spring.mvc.security.ctrl;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

public class Ctrl {

	// If user will be successfully authenticated he/she will be taken to the login secure page.
	@RequestMapping(value="/admin", method = RequestMethod.GET)
	public ModelAndView adminPage() {

		ModelAndView m = new ModelAndView();
		m.addObject("title", "Spring Security Custom Login Form Example");
		m.addObject("message", "This is protected page!");

		return m;

	// Spring security will see this message.
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(@RequestParam(value = "error", required = false) String error, 
			@RequestParam(value = "logout", required = false) String logout) {

		ModelAndView m = new ModelAndView();
		if (error != null) {
			m.addObject("error", "Invalid username and password error.");

		if (logout != null) {
			m.addObject("msg", "You have left successfully.");

		return m;

3.5 Create JSP views

Spring mvc supports many types of views for different presentation technologies.

3.5.1 Index page

Add the following code to the index page.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	    <title>Index page</title>    
		<h1>Spring Security Login via Database Example</h1>	
		<h1>This is welcome page!</h1>	
		<a id="secure" href="${pageContext.servletContext.contextPath}/admin">Goto secure page</a>

3.5.2 Custom login page

Add the following code to the custom login page in the Springsecuritywithdatabase/src/main/webapp/WEB-INF/views/ folder.


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    	<title>Custom login</title>
    	<style type="text/css">
    		.error {
    			color: #ff0000;
    			font-weight: bold;
    		.msg {
    			color: #008000;
    			font-weight: bold;
        <h1 id="banner">Custom login form</h1>
        <!-- invalid credentials error msg -->
        <c:if test="${not empty error}">
			<div class="error">${error}</div>
		<!-- logged out msg -->
		<c:if test="${not empty msg}">
			<div class="msg">${msg}</div>
		<!-- custom login form -->
        <form name="loginform" action="<c:url value='/login'/>" method="POST">
                    <td>Enter username:</td>
                    <td><input type='text' name='username' value=''></td>
                    <td>Enter password:</td>
                    <td><input type='password' name='password' /></td>
                    <td colspan="2"> </td>
                    <td colspan='2'><input name="submit" type="submit" value="Submit" /></td>

3.5.3 Secure page

Add the following code to the secure page in the Springsecuritywithdatabase/src/main/webapp/WEB-INF/views/ folder.


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" session="true" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	    <title>Secure page</title>    
		<h1>Title : ${title}</h1>
		<h1>Message : ${message}</h1>
		<!-- displaying the logged in user details. -->
		<c:if test="${pageContext.request.userPrincipal.name != null}">         
	       <span>Welcome: ${pageContext.request.userPrincipal.name}</span> | <span><a id="logout" href="${pageContext.servletContext.contextPath}/logout">Logout</a></span>

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Spring Security via Database Authentication - Deploy Application on Tomcat
Fig. 9: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page (as shown in fig. 10) will be displayed.


Server name (localhost) and port (8082) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Spring Security via Database Authentication - Index page
Fig. 10: Index page

Click the admin link. Spring security will intercept the request and redirect to /login and the custom login form is displayed.

Spring Security via Database Authentication - login form page
Fig. 11: Custom login form page

If the username and password are incorrect, the error message will be displayed as shown in fig. 12.

Spring Security via Database Authentication - Error message
Fig. 12: Error message

If the username and password are correct, spring will redirect to the originally requested url and display the secure page as shown in fig. 13.

Spring Security via Database Authentication - Secure page
Fig. 13: Secure page

Users can click the logout link to sign-out of the secure page as shown in fig. 14.

Spring Security via Database Authentication - Sign-out message
Fig. 14: Sign-out message

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to implement the custom login form and authenticate the users using a database in the spring security. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was a spring security tutorial to implement the user’s authentication via a database.

You can download the full source code of this example here: Springsecuritywithdatabase

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Newest Most Voted
Inline Feedbacks
View all comments
3 years ago

the tutorial is great as usual but there is a small mistake in the “security.xml” file i.e The database name is defined as “jdbc:mysql://localhost:3306/springsecuritydb” but it must be defined as “jdbc:mysql://localhost:3306/springwithhibernatedb” . Otherwise the program is running fine.

3 years ago

Well , I want ask one more question how to make changes in the roles of the users. i.e in this example every user is an “Admin” but if the developer wants some users to be assigned as “Admin” and some users as “Employee” and the users will have access to different pages according to their respective roles. How could we do it.

Anyway , thanks once again for these tutorials.

3 years ago
Reply to  Yatin

plz, make a tutorial on this.

Mr Morgan
Mr Morgan
3 years ago

Is a similar tutorial on Spring Boot security possible?