Spring Security - Basic Authentication
Last Updated :
05 May, 2025
Spring Security is a framework that allows a programmer to use JEE (Java Enterprise Edition) components to set security limitations on Spring Framework-based web applications. As a core part of the Spring ecosystem, it’s a library that can be utilized and customized to suit the demands of the programmer. Because it is a part of the same Spring family as Spring Web MVC, it works well together. The most significant benefit of this framework is that it is both strong and very adaptable. Although it adheres to Spring’s set-up conventions, programmers may select between default provisions and modify them to their specific requirements. Read more on Spring Security and its features in this article, Introduction to Spring Security and its Features.
In this article, we are going to learn how to implement basic authentication in a Spring MVC application using Spring Security. Basic Authentication sends user credentials with each HTTP request, and it's a straightforward way to protect web resources. We will walk through the steps of setting up Basic Authentication in a Spring Boot application and securing a simple UI.
A sample code is given below:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests() // Updated to 'authorizeHttpRequests' in newer versions
.anyRequest()
.authenticated()
.and()
.httpBasic(); // Configures HTTP Basic Authentication
}
Here we are using the httpBasic() element to define Basic Authentication by overriding the configure method.
Steps to Implement Basic Authentication with Spring Security
Step 1: Create a Spring Boot Project
We are going to use Spring Tool Suite IDE for this project. Please refer to this article to install STS in your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE. Create a Dynamic Web Project in your STS IDE. You may refer to this article to create a Dynamic Web Project in STS: How to Create a Dynamic Web Project in Spring Tool Suite?
Note: Spring Boot uses embedded Tomcat by default instead of requiring an external one.
Step 2: Folder Structure
Before moving to the project let’s have a look at the complete project structure for our Spring MVC application.
Folder Structure
Step 3: Add Dependencies to pom.xml File
Add the following dependencies to your pom.xml file:
- Spring Web
- Spring Security
- Spring Boot DevTools
XML
<dependencies>
<!-- Spring Web dependency for MVC setup -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Security for authentication and authorization -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Boot DevTools for enhanced development experience -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
Below is the complete pom.xml file. Please cross-verify if you have missed some dependencies.
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.springsecurity</groupId>
<artifactId>springsecurity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <!-- Change to jar if not using an external servlet container -->
<name>springsecurity Maven Webapp</name>
<url>http://www.gfg.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring Boot Web dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.1.0</version> <!-- Use the latest version -->
</dependency>
<!-- Spring Security for authentication and authorization -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>3.1.0</version> <!-- Use the latest version -->
</dependency>
<!-- Spring Boot DevTools for enhanced development experience -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope> <!-- DevTools for runtime use only -->
</dependency>
</dependencies>
<build>
<finalName>springsecurity</finalName>
<pluginManagement>
<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.10.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Step 4: Configure Dispatcher Servlet
Please refer to this article What is Dispatcher Servlet in Spring? and read more about Dispatcher Servlet which is a very very important concept to understand. Now, we are going to configure Dispatcher Servlet with our Spring MVC application.
Go to the src > main > java and create a class WebAppInitilizer. Below is the code for the WebAppInitilizer.java file.
File: WebAppInitilizer.java:
Java
package com.gfg.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null; // No root configuration needed for this example
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { MyAppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" }; // All requests are handled by this servlet
}
}
Step 5: Spring MVC Configuration
Create another class in the same location (src > main > java) and name it MyAppConfig. Configure Spring MVC to enable view resolution and component scanning. Below is the code for the MyAppConfig.java file.
File: MyAppConfig.java
Java
package com.gfg.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("com.gfg")
public class MyAppConfig {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
Reference article: Spring – Configure Dispatcher Servlet in Three Different Ways
Step 6: Create Your Spring MVC Controller
Create a simple controller to handle the request for /gfg. Go to the src > main > java > com.gfg.controller and create a class GfgController. Below is the code for the GfgController.java file.
File: GfgController.java
Java
package com.gfg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class GfgController {
@GetMapping("/gfg")
public String helloGfg() {
return "hello-gfg"; // View name
}
}
Reference article: Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
Step 7: Create Spring MVC View
Create a simple JSP page to display a message. Go to the src > main > webapp > WEB-INF > right-click > New > Folder and name the folder as views. Then views > right-click > New > JSP File and name your first view. Here, we have named it as hello-gfg.jsp file. Below is the code for the hello-gfg.jsp file. We have created a simple web page inside that file.
File: hello-gfg.jsp
HTML
<!DOCTYPE html>
<html>
<body bgcolor="green">
<h1>Hello GeeksforGeeks!</h1>
</body>
</html>
Reference article: How to Create Your First View in Spring MVC?
Step 8: Spring Security Configuration
Create a class to configure Spring Security and set up basic authentication. Go to the src > main > java > MySecurityAppConfig.
File: MySecurityAppConfig.java
Java
package com.gfg.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class MySecurityAppConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.builder()
.username("gfg")
.password(passwordEncoder().encode("gfg123"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.httpBasic(); // Enable Basic Auth
return http.build();
}
}
Step 9: Create Spring Security Initilizer
Initialize Spring Security in the application by registering the security filter chain. Go to the src > main > java and create a class SecurityInitializer. This class will help to register the spring security filter chain with our application. Below is the code for the SecurityInitializer.java file.
Note: This file is optional in Spring Boot 3.x but kept for backward compatibility.
File: SecurityInitializer.java
Java
package com.gfg.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
// Optional in Spring Boot 3.x+ (auto-configured)
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
// No code needed
}
Now we are done with setting up our Spring Security Filter Chain.
Now, let's run the application and test it out.
Step 10: Run Your Spring MVC Application
To run our Spring MVC Application right-click on your project > Run As > Run on Server. After that use the following URL to run your controller.
http://localhost:8080/springsecurity/gfg
And it will ask for authentication to use the endpoint and a pop-up screen will be shown like this.

Now sign in with the following credentials
- Username: gfg
- Password: gfg123
And now you can access your endpoint.
Similar Reads
What is Advanced Java?
In the realm of coding, creativity, and state-of-the-art technology have a pivotal role in the domain of software creation. Java is known for its platform independence, robustness, and extensive libraries. Advanced Java concepts let you make really complicated programs, it encompasses an array of te
13 min read
Dependency Injection(DI) Design Pattern
Effective dependency management is essential to building scalable and maintainable systems. The Dependency Injection (DI) design pattern is one strategy that has become very popular. Fundamentally, dependency injection is a method that addresses how components or objects are constructed and how they
10 min read
Spring
Introduction to Spring Framework
The Spring Framework is a powerful, lightweight, and widely used Java framework for building enterprise applications. It provides a comprehensive programming and configuration model for Java-based applications, making development faster, scalable, and maintainable.Before Enterprise Java Beans (EJB),
9 min read
Spring Framework Architecture
The Spring framework is a widely used open-source Java framework that provides a comprehensive programming and configuration model for building enterprise applications. Its architecture is designed around two core principles: Dependency Injection (DI) Aspect-Oriented Programming (AOP)The Spring fram
7 min read
Spring Initializr
Spring Initializr is a popular tool for quickly generating Spring Boot projects with essential dependencies. It helps developers set up a new application with minimal effort, supporting Maven and Gradle builds. With its user-friendly interface, it simplifies project configuration, making it an essen
4 min read
Spring - BeanFactory
The first and foremost thing when we talk about Spring is dependency injection which is possible because Spring is a container and behaves as a factory of Beans. Just like the BeanFactory interface is the simplest container providing an advanced configuration mechanism to instantiate, configure, and
4 min read
Spring - ApplicationContext
ApplicationContext belongs to the Spring framework. Spring IoC container is responsible for instantiating, wiring, configuring, and managing the entire life cycle of beans or objects. BeanFactory and ApplicationContext represent the Spring IoC Containers. ApplicationContext is the sub-interface of B
5 min read
Spring Dependency Injection with Example
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of
7 min read
Spring - IoC Container
The Spring framework is a powerful framework for building Java applications. It can be considered a collection of sub-frameworks, also referred to as layers, such as Spring AOP, Spring ORM, Spring Web Flow, and Spring Web MVC. We can use any of these modules separately while constructing a Web appli
2 min read
Spring - Autowiring
Autowiring in the Spring framework can inject dependencies automatically. The Spring container detects those dependencies specified in the configuration file and the relationship between the beans. This is referred to as Autowiring in Spring. To enable Autowiring in the Spring application we should
4 min read
Spring Framework Annotations
Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. Spring framework mainly focuses on providing various ways to help you manage your business obje
6 min read
SpringBoot
Introduction to Spring Boot
Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC, a commonly used module for building robust web applications. The major drawback of traditional Spring projects is that configuration can be time-consuming and overwhelming for new developers.
5 min read
Difference between Spring and Spring Boot
Spring Spring is an open-source lightweight framework that allows Java developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier
4 min read
Spring Boot - Architecture
Spring Boot is built on top of the core Spring framework. It simplifies and automates Spring-based application development by reducing the need for manual configuration. Spring Boot follows a layered architecture, where each layer interacts with other layers in a hierarchical order. The official Spr
3 min read
Spring Boot - Annotations
Spring Boot Annotations are a form of metadata that provides data about a spring application. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the
7 min read
Spring Boot Actuator
Developing and managing an application are the two most important aspects of the applicationâs life cycle. It is very important to know what is going on beneath the application. Also, when we push the application into production, managing it gradually becomes critically important. Therefore, it is a
5 min read
Spring Boot - Code Structure
There is no specific layout or code structure for Spring Boot Projects. However, there are some best practices followed by developers that will help us too. You can divide your project into layers like service layer, entity layer, repository layer,, etc. You can also divide the project into modules.
3 min read
Spring - RestTemplate
Due to high traffic and quick access to services, REST APIs are getting more popular and have become the backbone of modern web development. It provides quick access to services and also provides fast data exchange between applications. REST is not a protocol or a standard, rather, it is a set of ar
7 min read
How to Change the Default Port in Spring Boot?
Spring Boot framework provides a default embedded server i.e. the Tomcat server for many configuration properties to run the Spring Boot application. The application runs on the default port which is 8080. As per the application need, we can also change this default port for the embedded server. In
4 min read
Spring Boot - Scheduling
Spring Boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation. This article provides a step by step guideline on how we can schedule tasks to run in a spring boot application Implementation:It is depicted below stepwise as follows:Â St
4 min read
Spring Boot - Sending Email via SMTP
Spring Boot provides the ability to send emails via SMTP using the JavaMail Library. Here we will be illustrating step-by-step guidelines to develop Restful web services that can be used to send emails with or without attachments. In order to begin with the steps, let us first create a Spring Boot p
5 min read
Spring Boot - REST Example
In modern web development, most applications follow the Client-Server Architecture. The Client (frontend) interacts with the server (backend) to fetch or save data. This communication happens using the HTTP protocol. On the server, we expose a bunch of services that are accessible via the HTTP proto
4 min read
Introduction to the Spring Data Framework
Spring Data is a powerful data access framework in the Spring ecosystem that simplifies database interactions for relational (SQL) and non-relational (NoSQL) databases. It eliminates boilerplate code and provides an easy-to-use abstraction layer for developers working with JPA, MongoDB, Redis, Cassa
3 min read
Spring MVC
Spring - MVC Framework
The Spring MVC Framework follows the Model-View-Controller architectural design pattern, which works around the Front Controller, i.e., the Dispatcher Servlet. The Dispatcher Servlet handles and dispatches all incoming HTTP requests to the appropriate controller. It uses @Controller and @RequestMapp
4 min read
Spring - Multi Action Controller with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made
4 min read
Spring MVC using Java Based Configuration
Spring MVC framework enables the separation of modules, namely Model, View, and Controller, and seamlessly handles application integration. This enables the developer to create complex applications using plain Java classes. The model object can be passed between the view and the controller using map
3 min read
ViewResolver in Spring MVC
Spring MVC is a powerful Web MVC Framework for building web applications. It provides a structured way to develop web applications by separating concerns into Model, View, and Controller. One of the key features of Spring MVC is the ViewResolver, which enables you to render models in the browser wit
7 min read
Spring MVC - Exception Handling
Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your
6 min read
Spring - MVC Form Handling
Prerequisites: Spring MVC, Introduction to Spring Spring MVC is a Model-View-Controller framework, it enables the separation of modules into Model, View, and Controller and uniformly handles the application integration. In this article, we will create a student login form and see how Spring MVC hand
6 min read
How to Make Post Request in Java Spring?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
4 min read
Spring MVC CRUD with Example
In this article, we will explore how to build a Spring MVC CRUD application from scratch. CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic operations to create any type of project. Spring MVC is a popular framework for building web applications. Spring MVC follows
7 min read
What are Microservices?
Microservices are an architectural approach to developing software applications as a collection of small, independent services that communicate with each other over a network. Instead of building a monolithic application where all the functionality is tightly integrated into a single codebase, micro
12 min read