Spring Security 4 Tutorial

Spring Security is one of the most important modules of the Spring framework. It enables the developers to integrate the security features easily and in a managed way. In the following example, we will show how to implement Spring Security in a Spring MVC application.

Want to master Spring Framework ?
Subscribe to our newsletter and download the Spring Framework Cookbook right now!
In order to help you master the leading and innovative Java framework, we have compiled a kick-ass guide with all its major features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

1. Introduction

1.1 Spring Framework

1.2 Spring MVC Framework

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:

Fig. 1: Model View Controller (MVC) Overview

1.2.1 Spring MVC Architecture and Flow

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

Fig. 2: Spring MVC Architectural Diagram

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

1.3 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 take 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’s see how to implement the Spring Security in a Spring MVC application!

2. Spring Security 4 Example

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’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Spring Security Application Structure

2.3 Project Creation

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

Fig. 4: Create Maven Project

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

Fig. 5: Project Details

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

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.

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 Spring MVC, Spring Security Core, Spring Security Web, Spring Security Configuration etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependency for the Spring and Spring Security framework. In the Maven project file (pom.xml), developers will declare the following properties:

The updated file will have the following code:


<?xml version="1.0" encoding="UTF-8"?>
<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">
	<name>SpringSecurity Maven Webapp</name>
		<!-- Servlet API Dependency -->
		<!-- Spring Framework Dependencies -->
		<!-- Spring Security Dependencies -->
		<!-- JSTL Dependency -->

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.spring.mvc.security.

Fig. 9: Java Package Name (com.jcg.spring.mvc.security)

Once the package is created in the application, we will need to create the controller class. Right-click on the newly created package: New -> Class.

Fig. 10: Java Class Creation

A new pop window will open and enter the file name as: WebController. The controller class will be created inside the package: com.jcg.spring.mvc.security.

Fig. 11: Java Class (WebController.java)

3.2.1 Implementation of Controller Class

It is a simple class where the @Controller annotation is used to specify this class as a Spring controller. This controller is designed to handle 2 requests:

Add the following code to it:


package com.jcg.spring.mvc.security;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
public class WebController {
	@RequestMapping(value="/", method = RequestMethod.GET)
	public String visitHomePage() {
		return "index";
	@RequestMapping(value="/admin", method = RequestMethod.GET)
	public String visitAdministratorPage(ModelMap modelObj) {		
		modelObj.addAttribute("welcomeTitle", "Admministrator Control Panel");
		modelObj.addAttribute("messageObj", "This Page Demonstrates How To Use Spring Security!");
		return "admin";

3.3 Configuration Files

Let’s write all the configuration files involved in this application.

3.3.1 Spring & Spring Security Configuration Files

To configure the Spring Security framework, developers need to implement a bean configuration file i.e. spring-servlet.xml (provides an interface between the basic Java class and the outside world) and the spring-security.xml file to declare the authentication and authorization.

Right-click on SpringSecurity/src/main/webapp/WEB-INF folder, New -> Other.

Fig. 12: XML File Creation

A new pop window will open and select the wizard as an XML file.

Fig. 13: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as: SpringSecurity/src/main/webapp/WEB-INF and enter the file name as: spring-servlet.xml. Click Finish.

Fig. 14: spring-servlet.xml

Once the XML file is created, we will add the following code to it:


<?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"
	<context:component-scan base-package="com.jcg.spring.mvc.security" />
	<!-- 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" />


This file is loaded by the Spring’s Dispatcher Servlet which receives all requests coming into the application and dispatches processing for the controllers, based on the configuration specified in this spring-servlet.xml file. Let’s look at some default configurations:

Repeat the step (i.e. Fig. 12 and Fig. 13) and enter the filename as: spring-security.xml.

Fig. 15: spring-security.xml

Once the XML file is created, we will add the following code to it:


<?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"
	<http auto-config="true">
		<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
		<csrf disabled="true" />
				<user name="admin" password="pass@1234" authorities="ROLE_ADMIN" />


Here, there are two elements which are used for authentication and authorization purpose in Spring Security framework:

Do note, <csrf disabled="true" /> element tells the Spring Security Filter to intercept the /logout link as a HTTP GET request.

3.3.2 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 Spring Security will be loaded during the application startup time. 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 (i.e. spring-security.xml). Add the following code to it:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	<!-- Spring Configuration - Processes Application Requests -->
	<!-- Spring Security Filter Configuration -->

3.4 Creating JSP Views

Spring MVC supports many types of views for different presentation technologies. These include – JSP, HTML, XML etc. So let us write a simple view in SpringSecurity/src/main/webapp/WEB-INF/views.

Right-click on SpringSecurity/src/main/webapp/WEB-INF/views folder, New -> JSP File.

Fig. 16: JSP Creation

Verify the parent folder location as: SpringSecurity/src/main/webapp/WEB-INF/views and enter the filename as: index.jsp. Click Finish.

Fig. 17: index.jsp

This is very simple page with a heading “Spring Security Example” and a hyperlink to the administrator page. Add the following code to it:


<%@ page language="java" 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>Spring Security</title>
    <style type="text/css">
    	#adminPage {
    		text-decoration: none;
    		cursor: pointer;
    <div align="center">
        <h1>Spring Security Example</h1>
        <a id="adminPage" href="${pageContext.servletContext.contextPath}/admin">Go To Administrator Page</a>

Repeat the step (i.e. Fig. 16) and enter the filename as: admin.jsp.

Fig. 18: admin.jsp

This will be administrator page which requires the authentication and authorization to access. We are using the JSTL Expressions to display the title and the message in the model which will be provided by the controller class and if the user is logged in, we will display his username along with a Logout link. Add the following code it:


<%@ 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>Spring Security</title>
    <style type="text/css">
    	#titleId {    		 
    		color: red;
    		font-size: 34px;
    		margin: 36px 0px 15px 0px;
    	#messageId {
    		font-size: 24px;
    		margin: 15px 0px 15px 0px;
    	#welcomeMsgId {
    		font-size: 20px;
    		color: green;
    	#welcomeTextId {
    		text-transform: capitalize;
    	#logoutLink {
    		text-decoration: none;
    		cursor: pointer;
    <div id="welcomeMessage" align="center">
        <div id="titleId" class="">${welcomeTitle}</div>
        <div id="messageId" class="">${messageObj}</div>
        <c:if test="${pageContext.request.userPrincipal.name != null}">
            <div id="welcomeMsgId">
                <span id="welcomeTextId">Welcome: ${pageContext.request.userPrincipal.name}</span> | <span id="logoutId"><a id="logoutLink" 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.

Fig. 19: 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 will be displayed.


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

Fig. 20: Index Page

On this page, click on the Go to Administrator Page link. Spring Security will redirect you to the default login page.

Fig. 21: Default Login Page

Try to enter wrong credentials and Spring Security will automatically generate an error message at the top of the form.

Fig. 22: Invalid Credentials Error Message

Now enter the correct credentials as per the configuration (i.e. User: admin and Password: pass@1234) and Spring will take you to the Administrator Control Panel page.

Fig. 23: Administrator Page

Click on the Logout link and Spring Security filter automatically intercepts the /logout URL, invalidates the session and take you to the Login page again.

Fig. 24: Login Page

Notice the message You have been logged out appears. That’s all for this post. Happy Learning!

6. Conclusion

Hope, this article has been able to put some light on the basics of Spring Security Mechanism using XML configurations. That’s all for the Spring Security tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Spring Security.

You can download the full source code of this example here: Spring Security
Exit mobile version