Open In App

Spring Security XML Configuration

Last Updated : 05 Apr, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Spring Security is a robust and highly customizable framework that provides authentication and authorization for Java applications. While Java-based configuration is widely used today, XML-based configuration remains an important approach for legacy applications and projects requiring declarative security.

In this article, we will learn how to implement Spring Security XML Configuration in a Spring MVC web application. We will cover setting up dependencies, configuring security settings in XML, defining controllers, and securing URLs using role-based authentication.

Implementation: Here we will be creating a Spring MVC web application and adding xml-based configuration.

Steps to Configure Spring Security Using XML in a Spring MVC Application

Step 1: Create a Maven Web Application

Create a maven webapp project, we are using Eclipse IDE for creating this project. While creating a Maven project, select the archetype for this project as maven-archetype-webapp. Enter the group id and the artifact id for your project and click 'Finish.'


Project Structure:

After creating the project your project structure would look something like this:

Step 2: Add Dependencies in pom.xml File

Once the project is created, update the pom.xml file with the necessary dependencies, including:

  • spring-webmvc
  • spring-security-web
  • spring-security-core
  • spring-security-config
  • javax.servlet-api

pom.xml:  

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>com.gfg</groupId>
  <artifactId>SpringSecurityXmlConfig</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringSecurityXmlConfig Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.16</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>5.8.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.8.4</version>
</dependency>

  <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.8.4</version>
</dependency>


          
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

  </dependencies>

  <build>
    <finalName>SpringSecurityXmlConfig</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


Step 3: Configure web.xml (Deployment Descriptor)

The web.xml file acts as a bridge between the application and Spring Security. Add:

  • DispatcherServlet for request handling
  • ContextLoaderListener to load the application context
  • DelegatingFilterProxy to integrate security filters

web.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE xml>  
    <web-app 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_3_1.xsd"  
         version="3.1">  
          
        <servlet>  
            <servlet-name>gfg</servlet-name>  
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
            <load-on-startup>1</load-on-startup>  
        </servlet>  
        <servlet-mapping>  
            <servlet-name>gfg</servlet-name>  
            <url-pattern>/</url-pattern>  
        </servlet-mapping>  
          
        <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
        </listener>  
      
        <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>  
          
        <context-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>  
                /WEB-INF/gfg-servlet.xml  
                /WEB-INF/spring-security.xml  
            </param-value>  
        </context-param>  
</web-app>  


Step 4: Define Spring MVC Configuration in gfg-servlet.xml

The gfg-servlet.xml file:

  • Enables annotation-driven configuration
  • Configures component scanning
  • Defines InternalResourceViewResolver for JSP file mapping

gfg-servlet.xml:

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:mvc="http://www.springframework.org/schema/mvc"  
xmlns:context="http://www.springframework.org/schema/context"  
xsi:schemaLocation="  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd  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">  

   <mvc:annotation-driven />  
   
   <context:component-scan base-package="com.gfg.controller">  
   
   </context:component-scan>  
   
   <context:annotation-config></context:annotation-config>  
   
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
      <property name="prefix" value="/WEB-INF/views/"></property>  
      <property name="suffix" value=".jsp"></property>  
   </bean>  
   
</beans>  


Step 5: Set Up Spring Security in spring-security.xml

The spring-security.xml file is the core security configuration. Here, we:

  • Intercept HTTP requests for specific URL patterns
  • Configure authentication using an in-memory user with BCrypt password encoding

spring-security.xml:

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 auto-config="true"> 
            <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" /> 
    </http> 
    <authentication-manager>
    <authentication-provider>
        <!-- Changed from {noop} to BCrypt -->
        <password-encoder ref="bcryptEncoder"/>
        <user-service>
            <user name="admin" password="$2a$10$N9qo8uLO..." 
                  authorities="ROLE_ADMIN"/>
        </user-service>
    </authentication-provider>
  </authentication-manager>
  <beans:bean id="bcryptEncoder" 
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
</beans:beans>


Step 6: Create a Controller for Secured URLs

Define a WelcomeController.java class that handles requests for:

  • /: Welcome page
  • /admin: Admin page (accessible only by ROLE_ADMIN)

WelcomeController.java

Java
// Java Program to Illustrate WelcomeController Class

package com.gfg.controller;

// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

// Annotation
@Controller
// Class
public class WelcomeController {

    // Method 1
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String welcome()
    {
        return "welcome";
    }

    // Method 2
    @RequestMapping(value = "/admin",
                    method = RequestMethod.GET)
    public String
    admin()
    {
        return "admin";
    }
}


Step 7: Develop View Pages (JSP Files)

Create the following JSP files inside WEB-INF/views/:

  • welcome.jsp: Displays a welcome message
  • admin.jsp: Restricted to users with admin privileges and includes a logout form

This is the admin.jsp page in the views folder.

HTML
<html>  
<head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>Admin</title>  
    </head>  
<body>  
    Welcome Admin
    <form action="<%=request.getContextPath()%>/appLogout" method="POST">
       <input type="submit" value="Logout"/>
       <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>        
     </form> 
</body>  
</html>  


This is welcome.jsp page in the views folder.

HTML
<html>  
<head>  
    <meta content="text/html; charset=UTF-8">  
    <title>Home Page</title>  
</head>  
<body>  
    <h2>Welcome to Spring Security using XML Configuration!</h2>  
</body>  
</html>  


After creating all the configuration files and classes your project would look something like this:



Step 8: Run the Application and Test Security

Now that we have completed our project, it's time to run it on a tomcat server, just start the tomcat server and type http:localhost:8080/SpringSecurityXmlConfig/login.


Similar Reads