Spring Boot Security In-Memory Authentication Tutorial

In this tutorial, we will walk through the process of setting up in-memory authentication in a Spring Boot application using the latest version of Spring Security. We'll cover creating a simple Spring Boot application, configuring Spring Security for in-memory authentication, and securing a RESTful API.

What is In-Memory Authentication?

In-memory authentication is a simple way to configure users and roles directly within the Spring Security configuration without the need for a persistent database. This approach is useful for development, testing, or small applications where the user base is not expected to change frequently. User credentials and roles are stored in memory, making it a quick and easy way to secure an application.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed
  • Apache Maven installed
  • An IDE (Integrated Development Environment) like IntelliJ IDEA or Eclipse

Step 1: Setting Up the Project

Create a Spring Boot Project

  1. Open your IDE and create a new Spring Boot project using Spring Initializr.
  2. Add the following dependencies:
    • Spring Web
    • Spring Security

Project Structure

Your project structure should look like this:

spring-security-in-memory
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── security
│   │   │               ├── SecurityConfig.java
│   │   │               ├── SecurityApplication.java
│   │   │               └── controller
│   │   │                   └── HelloController.java
│   ├── main
│   │   └── resources
│   │       └── application.properties
└── pom.xml

Step 2: Adding Dependencies

Add the necessary dependencies for Spring Security and Spring Web in the pom.xml file.

pom.xml

    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Starter Security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- Spring Boot Starter Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Step 3: Configuring Spring Security for Basic Authentication

Update the SecurityConfig class to configure Spring Security for HTTP Basic authentication.

SecurityConfig.java

package com.example.security;

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.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorizeRequests ->
                authorizeRequests
                    .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();

        UserDetails admin = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("admin")
            .roles("ADMIN")
            .build();

        return new InMemoryUserDetailsManager(user, admin);
    }
}

Explanation

  • securityFilterChain(HttpSecurity http): Configures the security filter chain to require authentication for all requests and enable HTTP Basic authentication with httpBasic(withDefaults()).
  • userDetailsService(): Configures an in-memory user store with two users: user with role USER and admin with role ADMIN. The withDefaultPasswordEncoder method is used to encode passwords.

Step 4: Creating the Hello Controller

The HelloController class remains the same as in the previous steps.

HelloController.java

package com.example.security.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

Step 5: Creating the Main Application Class

The main application class also remains the same.

SecurityApplication.java

package com.example.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityApplication.class, args);
    }
}

Step 6: Running the Application

To run the application, execute the SecurityApplication class. This will start the Spring Boot application with Spring Security configured for HTTP Basic authentication.

Accessing the Application

  1. Open your browser or a tool like Postman and navigate to http://localhost:8080/api/hello.
  2. You will be prompted to enter a username and password.
  3. Use the credentials defined in the SecurityConfig class:
    • username: user
    • password: password
    • username: admin
    • password: admin

Using curl to Access the API

You can also use curl to access the secured API:

curl -u user:password http://localhost:8080/api/hello

This command sends a request to the API with HTTP Basic authentication using the user credentials.

Conclusion

In this tutorial, we have walked through setting up a basic Spring Boot application and integrating it with Spring Security for in-memory authentication suitable for securing a REST API. We configured Spring Security to use HTTP Basic authentication and created a simple RESTful API endpoint. By following this tutorial, you should now have a good understanding of how to integrate Spring Security with Spring Boot and secure your REST APIs using in-memory authentication.


Comments