spring

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.
 
 
 
 
 
 
 
 

1. Introduction

1.1 Spring Framework

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
    • Support for Transaction Management
    • Support for interaction with the different databases
    • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
    • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
    • Support for REST style web-services

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:

  • Model (M): Model’s responsibility is to manage the application’s data, business logic, and the 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 spring framework, the controller part is played by the Dispatcher Servlet

Fig. 1: Model View Controller (MVC) Overview
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
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.

  • 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 it can be used by view to display the result to the user

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
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
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
Fig. 5: Project Details

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

Fig. 6: 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.

Fig. 7: 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>SpringSecurity</groupId>
	<artifactId>SpringSecurity</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

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:

  • spring-security-core: It contains the core authentication and access-control classes and interfaces
  • spring-security-web: It contains filters and related web-security infrastructure code. It also enables the URL based security which we are going to use in this demo
  • spring-security-config: It contains the security namespace parsing code. Developers need it if they are using the Spring Security XML file for configuration
  • spring-security-taglibs: It provides the basic support for accessing the security information and applying security constraints in JSP

The updated file will have the following code:

pom.xml

<?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">
	<modelVersion>4.0.0</modelVersion>
	<groupId>SpringSecurity</groupId>
	<artifactId>SpringSecurity</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringSecurity 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>
		<!-- JSTL Dependency -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

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
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)
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
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)
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:

  • /: Request to the application’s context root or the home page
  • /admin: Request to the administrator page, which will be secured by Spring security

Add the following code to it:

WebController.java

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;

@Controller
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
Fig. 12: XML File Creation

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

Fig. 13: Wizard Selection
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
Fig. 14: spring-servlet.xml

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

spring-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.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" />
	</bean>
</beans>

Notes:

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:

  • InternalResourceViewResolver: This bean declaration tells the framework how to find the physical JSP files according to the logical view names returned by the controllers, by attaching the prefix and the suffix to a view name. For e.g. If a controller’s method returns home as the logical view name, then the framework will find a physical file home.jsp under the /WEB-INF/views directory
  • <context:component-scan>: This tell the framework which packages to be scanned when using the annotation-based strategy. Here the framework will scan all classes under the package: com.jcg.spring.mvc.example

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

Fig. 15: spring-security.xml
Fig. 15: spring-security.xml

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

spring-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">

	<http auto-config="true">
		<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
		<csrf disabled="true" />
	</http>

	<authentication-manager>
		<authentication-provider>
			<user-service>
				<user name="admin" password="pass@1234" authorities="ROLE_ADMIN" />
			</user-service>
		</authentication-provider>
	</authentication-manager>
</beans:beans>

Notes:

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

  • The <authentication-manager> element declares a user with username, password and role. This user can be authenticated to access the application
  • In the <http> element, developers declare which URL pattern will be intercepted by the Spring Security Filter, using the <intercept-url> element
  • <authentication-provider> element, specifies the username and password provider. Here we have used hard-coded username (admin) and password (pass@1234) values.

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:

web.xml

<?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"
	version="2.5"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee              
										  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<!-- Spring Configuration - Processes Application Requests -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</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/spring-security.xml</param-value>
	</context-param>
	<!-- Spring Security Filter 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.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
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
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:

index.jsp

<%@ 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">
<html>

<head>
    <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;
    	}
    </style>
</head>

<body>
    <div align="center">
        <h1>Spring Security Example</h1>
        <a id="adminPage" href="${pageContext.servletContext.contextPath}/admin">Go To Administrator Page</a>
    </div>
</body>

</html>

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

Fig. 18: 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:

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>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;
    	}
    </style>
</head>

<body>
    <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>
            </div>
        </c:if>
    </div>
</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.

Fig. 19: How to Deploy Application on Tomcat
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.

http://localhost:8085/SpringSecurity

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
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
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
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
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
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.

Download
You can download the full source code of this example here: Spring Security

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).
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button