Open In App

Spring Security - Basic Authentication

Last Updated : 05 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

File-Strcture.png
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.


Next Article
Practice Tags :

Similar Reads