Spring Security 4 XML Config In Memory Authentication Intercept Url Security Method

August 28, 2015 | Updated last November, 2015 | 1394 views | Comments

A full JAVA authentication and authorization web application showcasing the use of "Web Security Expressions" through intercept-url elements of "Spring Security 4" configured with XML on top of "Annotation Driven Spring WebMVC Framework 4".

 

Built and tested with the following:

  • Eclipse Juno IDE
  • Apache Tomcat 7.0.47
  • JDK 1.7.0
  • Maven 3.0.4
  • Spring Web-MVC Framework 4.2.2
    • Configuration: XML
    • Url Mapping: Annotation
  • Spring Security 4.0.2
    • Configuration: XML
    • Authentication: In Memory
    • Security Method: Intercept Url

 

Task: Develop a Teacher-Student authentication and authorization system. A Student can login and access the Student Page, the Teacher, at the same time, can also login, and aside from having the access to the Teacher Page, a Teacher can also access the Student Page. The requirement is to build the application under Spring WebMVC Framework 4 configured with annotation mapping along with Spring Security 4 XML Configuration Style and the Intercept Url Security Method.

 

Step 1. Create a new Maven Project.

Enter the following details:

  • Group Id: com.consistentcoder
  • Artifact Id: basic-spring-security-4-intercept-url
  • Name: basic spring security 4 intercept url

Tutorials:
Create a New Maven Project in Eclipse
Configure Run on Server option on a Maven Project on Eclipse IDE

 

Your Maven Project Structure should look something like below.

 

Step 2. Edit pom.xml file.

The following code are the contents of it.

<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.consistentcoder</groupId>
    <artifactId>basic-spring-security-4-intercept-url</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>basic spring security 4 intercept url</name>
  
    <properties>
        <spring.version>4.2.2.RELEASE</spring.version>
        <springSecurity.version>4.0.2.RELEASE</springSecurity.version>
    </properties>
  
    <dependencies>
        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        
        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${springSecurity.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${springSecurity.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${springSecurity.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${springSecurity.version}</version>
        </dependency>
    </dependencies>
</project>

/pom.xml

 

Step 3. Edit web.xml file.

Replace current code with the code below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>basic-spring-security-4-intercept-url</display-name>
  
    <!-- Spring Framework -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Spring Security -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <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>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>
</web-app>

/src/main/webapp/WEB-INF/web.xml

 

Step 4. Create spring-servlet.xml file.

Create a new XML file ("spring-servlet.xml") on the same folder where "web.xml" is located.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:sec="http://www.springframework.org/schema/security"
	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.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <context:component-scan base-package="com.consistentcoder.controllers" />
    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/resources/" />
    
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>

/src/main/webapp/WEB-INF/spring-servlet.xml

 

Step 5. Create spring-security.xml file.

Still on the same folder, create another XML file ("spring-security.xml") , and put the following code on 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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.xsd">

    <http auto-config="true">
        <form-login />
        <logout invalidate-session="true" />
        <intercept-url pattern="/teacher/**" access="hasAnyRole('ROLE_TEACHER')"/>
        <intercept-url pattern="/student/**" access="hasAnyRole('ROLE_STUDENT','ROLE_TEACHER')"/>
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="teacher" password="teacher" authorities="ROLE_TEACHER" />
                <user name="student" password="student" authorities="ROLE_STUDENT" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

/src/main/webapp/WEB-INF/spring-security.xml

 

Step 6. Create the template files.

Step 6.1. Create the folder.

A new folder named "jsp" should be created inside "WEB-INF" folder.

 

Step 6.2. Create the home page template file.

Create a new ".jsp" file ("index.jsp") inside the new folder "jsp", and place the following code inside 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome! - ConsistentCoder.com</title>
</head>
<body>
<h1>${ message }</h1>
<p>
    <a href="<%=request.getContextPath()%>/teacher">Teacher Page</a> | <a href="<%=request.getContextPath()%>/student">Student Page</a> | <a href="<%=request.getContextPath()%>/login">Login</a>
</p>
<p><u>Teacher login details</u></p>
<p>
    <ul>
        <li>username: <strong>teacher</strong></li>
        <li>password: <strong>teacher</strong></li>
    </ul>
</p>
<p><u>Student login details</u></p>
<p>
    <ul>
        <li>username: <strong>student</strong></li>
        <li>password: <strong>student</strong></li>
    </ul>
</p>
</body>
</html>

/src/main/webapp/WEB-INF/js/index.jsp

 

Step 6.3. Create the student page template file.

Inside folder "jsp", another folder should be created, name it "student". Inside it, create a new ".jsp" file with the name "student.jsp" and put the following code on 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Page - ConsistentCoder.com</title>
</head>
<body>
<h1>${ message }</h1>
<p>
    <form id="logout" action="<%=request.getContextPath()%>/logout" method="post" >
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
        <input type="submit" value="logout" />
    </form>
</p>
</body>
</html>

/src/main/webapp/WEB-INF/js/student/student.jsp

 

Step 6.4. Create the teacher page template file.

Create another folder inside the folder "jsp", name it "teacher", and inside it, create a new ".jsp" file ("teacher.jsp"). Enter the following code inside 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Teacher Page - ConsistentCoder.com</title>
</head>
<body>
<h1>${ message }</h1>
<p>You can also check the <a href="<%=request.getContextPath()%>/student">Student Page</a></p>
<p>
    <form id="logout" action="<%=request.getContextPath()%>/logout" method="post" >
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
        <input type="submit" value="logout" />
    </form>
</p>
</body>
</html>

/src/main/webapp/WEB-INF/js/teacher/teacher.jsp

 

The jsp template file structure should look similar with the image below.

 

Step 7. Create the Controller Class.

Create a new package and name it "com.consistentcoder.controllers". Inside that newly created package, create a new class with the name "Main".

Tutorials:
Create a New Package on Eclipse IDE
Create a New JAVA Class on Eclipse IDE

package com.consistentcoder.controllers;

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 Main {
	@RequestMapping(value = "/", method = RequestMethod.GET)
    public String indexPage(ModelMap model) {

        model.addAttribute("message", "Hello Guest, this is the Home Page...");
        return "index";
    }
    
    @RequestMapping(value = "/teacher", method = RequestMethod.GET)
    public String teacherPage(ModelMap model) {
        
        model.addAttribute("message", "Teacher Page...");
        return "teacher/teacher";
    }
    
    @RequestMapping(value = "/student", method = RequestMethod.GET)
    public String studentPage(ModelMap model) {
        
        model.addAttribute("message", "Student Page...");
        return "student/student";
    }
}

/src/main/java/com/consistentcoder/constrollers/Main.java

 

That's all!

Spring Security 4 XML Config with Intecept Url Security Method has been developed.

 

Final Project Structure

 

What's Next? Test the application.

Browse the following link after you had started your server. http://localhost:8080/basic-spring-security-4-intercept-url. "Home Page" will be displayed.

 

Clicking on the Student Page and/or the "Teacher Page" will redirect the guest to the login page.

 

Login with Teacher details and visit the "Teacher Page".

 

Login with Teacher details and visit the "Student Page".

 

Login with Student details and visit the "Teacher Page".

 

Login with Student details and visit the "Student Page".

 

Login with Incorrect details.

 

"Logout".