Home  >  Spring 5

Spring Security XML Configuration Example

By Arvind Rai, December 09, 2019
Spring Security is configured using <http> element in XML configuration file. When we use <http> element, Spring Security creates FilterChainProxy bean with bean name springSecurityFilterChain. The configuration within <http> element is used to build a filter chain within FilterChainProxy. We can use more <http> elements to add extra filter chains. All the filters which require a reference to AuthenticationManager will be automatically injected. Each <http> namespace block creates a SecurityContextPersistenceFilter, an ExceptionTranslationFilter and a FilterSecurityInterceptor and they can not be replaced with alternatives.
Find the minimal <http> configuration.
<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.xsd
	http://www.springframework.org/schema/security
	http://www.springframework.org/schema/security/spring-security.xsd">

   <http />
   
   <authentication-manager>
      <authentication-provider>
	    <user-service>
	        <user name="Amit" password="{noop}amit123" authorities="ROLE_USER" />		        
	    </user-service>	
      </authentication-provider>
   </authentication-manager>
</b:beans> 
Here on this page we will create a Spring Security demo application with XML configuration.


Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.2.1.RELEASE
3. Spring Boot 2.2.1.RELEASE
4. Tomcat 9
5. Maven 3.5.2

Maven Dependency

Find the Maven dependencies.
pom.xml
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.2.1.RELEASE</version>
	<relativePath />
</parent>
<properties>
	<context.path>spring-app</context.path>
	<java.version>11</java.version>
</properties>
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency>
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>
</dependencies> 

Create Spring Security XML

Find the Spring Security XML configuration being used in our demo application.
security-config.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.xsd
	http://www.springframework.org/schema/security
	http://www.springframework.org/schema/security/spring-security.xsd">
	<http>
		<intercept-url  pattern="/admin/**" access="hasRole('ADMIN')" />
		<intercept-url  pattern="/user/**" access="hasAnyRole('USER', 'ADMIN')" />		
		<form-login 
		   login-page="/customLogin.jsp" 
		   login-processing-url="/appLogin"
		   username-parameter="username"
		   password-parameter="password"
		   default-target-url="/user"/>
		<logout 
		   logout-url="/appLogout" 
		   logout-success-url="/customLogin.jsp"/>  
		<access-denied-handler error-page="/error"/>
	</http>
	<authentication-manager>
		<authentication-provider>
		    <user-service>
		        <user name="Namo" password="{noop}namo123" authorities="ROLE_ADMIN" />
		        <user name="Amit" password="{noop}amit123" authorities="ROLE_USER" />		        
		    </user-service>	
		</authentication-provider>
	</authentication-manager>
</beans:beans> 
Find the child elements of <http>.
<intercept-url>: Defines the set of URL patterns that the application will accept and handle it.
<form-login>: Provides login form to accept username/password.
<logout>: Handles logout of the application.
<access-denied-handler>: Defines error page for access denied.

The <authentication-manager> element registers AuthenticationManager that provides authentication service to the application.
The <authentication-provider> configures UserDetailsService with user-service-ref attribute.

Find the Spring MVC XML configuration.
app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	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.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
        
	<context:component-scan base-package="com.concretepage" />
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	  <property name="prefix" value="/WEB-INF/secure/"/>
	  <property name="suffix" value=".jsp"/> 
    </bean>
</beans> 

Configure DelegatingFilterProxy in web.xml

The <http> element configurations allow Spring Security to create Filter bean with bean name springSecurityFilterChain in our application. This bean will be responsible for all the securities such as protecting the application URLs, validating submitted username and password, redirecting to login form, etc.
In web.xml we need to configure a filter named as DelegatingFilterProxy which looks for a Spring bean by the name of filter (for eg. springSecurityFilterChain) and delegates all works to that bean. Find the web.xml being used in our application.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
        http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">

	<display-name>Spring Security Example</display-name>
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/app-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</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-config.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>
</web-app> 

Create Controller

AppController.java
package com.concretepage.controller;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class AppController {
	@RequestMapping(value="/admin")
	public String adminInfo(ModelMap model, Authentication authentication) {
		model.addAttribute("name", authentication.getName());
 		return "info";
 	}
	@RequestMapping(value="/user")
	public String userInfo(ModelMap model, Authentication authentication) {
		model.addAttribute("name", authentication.getName());
 		return "info";
 	}	
	@RequestMapping(value="/error")
	public String error() {
 		return "access-denied";
 	}
} 

Create View

customLogin.jsp
<html>
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
        <h3>Spring Security Example</h3>
        <font color="red">
		   ${SPRING_SECURITY_LAST_EXCEPTION.message}
        </font>
		<form action="<%=request.getContextPath()%>/appLogin" method="POST">
			Enter UserName:	<input type="text" name="username"/><br/><br/>
			Enter Password: <input type="password" name="password"/> <br/><br/>			
			<input type="submit" value="Login"/>
			<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>			
		</form>
    </body>
</html> 
info.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
      <h3>Hello <c:out value="${name}"/></h3>
      <form action="<%=request.getContextPath()%>/appLogout" method="POST">
        <input type="submit" value="Logout"/>
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>		
      </form>      
    </body>
</html> 
access-denied.jsp
<html>
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
      <h3>You are not authorized to access this page.</h3>
      <form action="<%=request.getContextPath()%>/appLogout" method="POST">
        <input type="submit" value="Logout"/>
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>		
      </form> 
    </body>
</html> 

Output

Deploy the code in Tomcat and access the URL.
http://localhost:8080/spring-app/user 
We will see login page.
Spring Security XML Configuration Example

Reference

Spring Security Reference

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2020 concretepage.com | Privacy Policy | Contact Us