The Wayback Machine - https://web.archive.org/web/20240526223658/https://www.geeksforgeeks.org/spring-security-xml/
Open In App

Spring Security XML

Last Updated : 24 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Spring Security is a powerful way to provide authentication as well as authorization to Spring application. Spring Security is a powerful tool that provides the feature of custom security configuration to the user, security configuration in spring can be customized in two ways as listed below as follows:

  • XML-based configuration
  • Java configuration.

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

Prerequisites: Introduction to Spring

Steps to Create an XML-Based Configuration in Spring MVC

Step 1: 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.’

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

The pom.xml file defines all the dependencies required for the project. Make sure to add all the dependencies mentioned in this file for your project to work properly.

File: pom.xml  

XML




<?xml version="1.0" encoding="UTF-8"?>
  
  <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.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.16</version>
</dependency>
  
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>5.6.2</version>
</dependency>
  
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.6.2</version>
</dependency>
  
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.6.2</version>
</dependency>
  
  
            
<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>
        <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>


The web.xml defines mapping with different URLs and servlets to handle requests for those URLs. Spring DelegatingFilterProxy provides link between web.xml and application context.

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


The gfg-servlet.xml file handles all HTTP requests for the web applications. The annotation-driven enable the spring annotation classes. The component scan locates and allocated beans according to the defined annotation. The bean configuration helps in identifying and locating JSP files in the project.

FIle: gfg-servlet.xml

XML




<?xml version="1.0" encoding="UTF-8"?>  
  
   <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>


This is where you define the configuration for spring security, the http bean helps in intercepting all the http calls mentioned in the file, the user-service in the authentication-provider in the authentication-manager creates a user for the application with the username, password, and the role for that user. 

XML




<?xml version="1.0" encoding="UTF-8"?> 
  
    <http auto-config="true"> 
            <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" /> 
    </http> 
    <authentication-manager> 
        <authentication-provider> 
           <user-service> 
                   <user name="admin" password="{noop}pass" authorities="ROLE_ADMIN" /> 
           </user-service> 
       </authentication-provider> 
   </authentication-manager> 
   <beans:bean id ="passwordEncoder" 
      class = "org.springframework.security.crypto.password.NoOpPasswordEncoder" 
      factory-method = "getInstance">
   </beans:bean> 
</beans:beans>


The WelcomeController class in the com.gfg.controller package defines the mappings for url, in this project we have defines two GET methods for two URLs. The welcome method redirects to the home view page and the admin method does it for the admin view page.

File: 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";
    }
}


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>


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

Step 4: 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.



Previous Article
Next Article

Similar Reads

Spring Security - security none, filters none, access permitAll
In Spring Boot, Spring Security is the most powerful authentication and access control framework for Java applications. Spring Security provides strong security features to protect our web applications from various security threats such as authentication, authorization, session management, and web vulnerabilities. It is highly flexible and easy to
6 min read
Spring - Add User Name and Password in Spring Security
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. Like all Spring projects, the real power of Spring Security is fou
3 min read
Spring - Add Roles in Spring Security
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. Like all Spring projects, the real power of Spring Security is fou
4 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorizatio
2 min read
Authentication and Authorization in Spring Boot 3.0 with Spring Security
In Spring Security 5.7.0, the spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes in Spring Security. So in this article, we will understand how to perform spring security authentication and authorization using spring bo
3 min read
Spring Boot 3.0 - JWT Authentication with Spring Security using MySQL Database
In Spring Security 5.7.0, the spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes inSpring Security . In this article, we'll learn how to implement JWT authentication and authorization in a Spring Boot 3.0 application us
7 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Spring - AOP AspectJ Xml Configuration
Spring allows you to specify aspects, recommendations, and pointcuts in an XML file. Annotations were used in the aop examples on the preceding page. The XML configuration file will now show us the same samples. Let's look at the XML components that describe advice. aop:before: It's used before the real business logic procedure is called.aop:after:
7 min read