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

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

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:

pom.xml

<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">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring.security.database</groupId>
	<artifactId>Springsecuritywithdatabase</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

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.

pom.xml

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring.security.database</groupId>
	<artifactId>Springsecuritywithdatabase</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Springsecuritywithdatabase Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<!-- Servlet API Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
		</dependency>
		<!-- Spring Framework Dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.2.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.2.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.2.4.RELEASE</version>
		</dependency>
		<!-- Spring Security Dependencies -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
		<!-- Spring JDBC dependency -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
		<!-- Mysql connector dependency -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.13</version>
		</dependency>
		<!-- JSTL Dependency -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

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. -----
CREATE DATABASE IF NOT EXISTS springsecuritydb;

USE springsecuritydb;

----- User credentials table. -----
CREATE TABLE USERS (
	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. -----
CREATE TABLE USERS_ROLES (
  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.xml

<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 -->
	<servlet>
		<servlet-name>springmvcsecurity</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvcsecurity</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/security.xml</param-value>
	</context-param>

	<!-- spring security configuration -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

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.

springmvcsecurity-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
		http://www.springframework.org/schema/context  
		http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <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 -->
    <bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

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.

security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
	xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    			    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    			    http://www.springframework.org/schema/security
   			        http://www.springframework.org/schema/security/spring-security-4.0.xsd">

	<!-- 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" />
	</http>

	<!-- spring authentication configuration via database -->
	<authentication-manager>
		<authentication-provider>
			<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 = ?" />
		</authentication-provider>
	</authentication-manager>

	<!-- database configuration (database = MySql) -->
	<beans:bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<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="" />
	</beans:bean>
</beans:beans>

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.

Ctrl.java

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;

@Controller
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!");
		m.setViewName("admin");

		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.");
		}

		m.setViewName("login");
		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.

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	    <title>Index page</title>    
	</head>
	<body>
		<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>
	</body>
</html>

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.

login.jsp

<%@ 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">
<html>
	<head>
    	<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;
    		}
    	</style>
	</head>
    <body>
        <h1 id="banner">Custom login form</h1>
        
        <!-- invalid credentials error msg -->
        <c:if test="${not empty error}">
			<div class="error">${error}</div>
		</c:if>
		
		<!-- logged out msg -->
		<c:if test="${not empty msg}">
			<div class="msg">${msg}</div>
		</c:if>
		
		<!-- custom login form -->
        <form name="loginform" action="<c:url value='/login'/>" method="POST">
            <table>
                <tr>
                    <td>Enter username:</td>
                    <td><input type='text' name='username' value=''></td>
                </tr>
                <tr>
                    <td>Enter password:</td>
                    <td><input type='password' name='password' /></td>
                </tr>
                <tr>
                    <td colspan="2"> </td>
                </tr>
                <tr>
                    <td colspan='2'><input name="submit" type="submit" value="Submit" /></td>
                </tr>
            </table>
        </form>
    </body>
</html>

3.5.3 Secure page

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

admin.jsp

<%@ 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">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	    <title>Secure page</title>    
	</head>
	<body>
		<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>
	    </c:if>
	</body>
</html>

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.

http://localhost:8082/Springsecuritywithdatabase/

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.

Download
You can download the full source code of this example here: Springsecuritywithdatabase
(+2 rating, 4 votes)
5 Comments Views Tweet it!

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

 

5
Leave a Reply

avatar
3 Comment threads
2 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
ankitMr MorganYatin Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
ankit
Guest
ankit

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.

ankit
Guest
ankit

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.

Mr Morgan
Guest
Mr Morgan

Is a similar tutorial on Spring Boot security possible?