Spring Security 4 XML Config In Memory Authentication Annotation Security Method

August 21, 2015 | Updated last October, 2015 | 4354 views | Comments

Secure JAVA web apps with an "XML-Configured Spring Security 4 Framework" using the "Pre Annotation Security Method (Method Security Expressions) " with "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: Annotation

 

Task: Create an authentication and authorization system wherein a member and an admin user can login. Each user type will have their specific authorized pages, the admin, however, aside from his own admin page, can also access the member page. Requirement is to make use of the Spring Security 4 XML Configuration Style and the Pre-Annotation Security Method together with Spring WebMVC Framework 4 configured with annotation mapping.

 

Step 1. Create a new Maven Project.

Enter the following details:

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

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

After you have followed the tutorials above, your Maven Project Structure would look something like below.

 

Step 2. Edit pom.xml file.

Put the code below inside 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</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>basic spring security 4</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.

Inside it, it will have the following code.

<?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</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 on the same folder where "web.xml" is located, name it "spring-servlet.xml".

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

    <sec:global-method-security pre-post-annotations="enabled" />   
    <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, name it "spring-security.xml", and have the following code inside 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" />
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="admin" authorities="ROLE_ADMIN" />
                <user name="member" password="member" authorities="ROLE_MEMBER" />
            </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.

Inside "WEB-INF" folder, create a new folder, name it "jsp".

 

Step 6.2. Create the home page template file.

Inside the new folder "jsp" create a new ".jsp" file, name it "index.jsp", and put 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()%>/admin">Admin Page</a> | <a href="<%=request.getContextPath()%>/member">Member Page</a> | <a href="<%=request.getContextPath()%>/login">Login</a>
</p>
<p><u>Admin login details</u></p>
<p>
    <ul>
        <li>username: <strong>admin</strong></li>
        <li>password: <strong>admin</strong></li>
    </ul>
</p>
<p><u>Member login details</u></p>
<p>
    <ul>
        <li>username: <strong>member</strong></li>
        <li>password: <strong>member</strong></li>
    </ul>
</p>
</body>
</html>

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

 

Step 6.3. Create the member page template file.

Inside folder "jsp", create another folder, name it "member". Then inside it, create a new ".jsp" file, name it "member.jsp". Now, put the following code inside that "member.jsp" file.

<%@ 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>Member 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/member/member.jsp

 

Step 6.4. Create the admin page template file.

Create another folder inside the folder "jsp", name it "admin". Then inside it, create a new ".jsp" file, name it "admin.jsp". Now, put 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>Admin Page - ConsistentCoder.com</title>
</head>
<body>
<h1>${ message }</h1>
<p>You can also check the <a href="<%=request.getContextPath()%>/member">Member 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/admin/admin.jsp

 

This is how the jsp template file structure should look like.

 

Step 7. Create the Controller Class.

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

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

package com.consistentcoder.controllers;

import org.springframework.security.access.prepost.PreAuthorize;
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";
    }
    
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public String adminPage(ModelMap model) {
        
        model.addAttribute("message", "Admin Page...");
        return "admin/admin";
    }
    
    @PreAuthorize("hasAnyRole('ROLE_MEMBER','ROLE_ADMIN')")
    @RequestMapping(value = "/member", method = RequestMethod.GET)
    public String memberPage(ModelMap model) {
        
        model.addAttribute("message", "Member Page...");
        return "member/member";
    }
}

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

 

That's all!

Spring Security 4 XML Config with Annotation Security Method has been developed.

 

Final Project Structure

 

What's Next? Test the application.

Start your server and browse this link. http://localhost:8080/basic-spring-security-4/. "Home Page" will be displayed.

 

Click the "Admin Page" link. You will be redirected to the "Login Page".

 

Click the "Member Page" link. Again, you will be redirected to the "Login Page".

 

Click the "Login" link. As expected, you will be redirected to the "Login Page".

 

Login with the "Admin details" and go to the "Admin Page".

 

Login with the "Admin details" and go to the "Member Page".

 

Login with the "Member details" and go to the "Admin Page".

 

Login with the "Member details" and go to the "Member Page".

 

Login with "Incorrect details".

 

"Logout".