Spring Security in Memory Authentication in Spring Boot

In this example, we will learn how to use Spring Security in Memory Authentication in Spring Boot REST API example. We will create an example REST API in Spring Boot where we will retrieve the username of the user through the REST API endpoint. InMemoryUserDetailsManager class is a non-persistent implementation of the UserDetailsManager interface which is backed by an in-memory map.UserDetails provides user information. User class is a Models core user information retrieved by a UserDetailsService

Table of content

1. Keep Eclipse IDE ready(STS integrated)
2. Create a Spring Boot Starter Project 
3. Maven Dependency
4. Define configuration in the application.properties file
5. Create a Spring Security Configuration class
6. Create a Controller
7. Run the app
8. Conclusion

1. Keep Eclipse IDE ready(STS integrated)

Refer to this article How to Create Spring Project in IDE to create Spring Boot Project in Eclipse IDE.

2. Create a Spring Boot Starter Project 

Add the following dependencies: 
   • Spring Web
   • Spring Security

Project Structure of Spring Security in Memory Authentication in Spring Boot

3. Maven Dependency

pom.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.11</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springjava</groupId>
    <artifactId>Spring_Security_In_Memory_Authentication_Example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Spring_Security_In_Memory_Authentication_Example</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>16</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

4. Define configuration in the application.properties file

server.port=8899

5. Create a Spring Security Configuration class

SecurityConfig.java

package com.springjava.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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
public class SecurityConfig {

    @Bean
    public static PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeHttpRequests((authorize) -> {
            authorize.anyRequest().authenticated();
        }).httpBasic(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        
        UserDetails peter = User.builder().username("peter").password(passwordEncoder().encode("peter@123")).roles("USER")
                .build();
        
        UserDetails admin = User.builder().username("admin").password(passwordEncoder().encode("admin")).roles("ADMIN")
                .build();
        return new InMemoryUserDetailsManager(peter,admin);
    }
}

6. Create a Controller

UserController.java

package com.springjava.controller;

import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    
    @GetMapping("/user")
    public String getUser(Authentication authentication) {
        return "Hello Spring Security"+authentication.getName();
    }
}

→ In the above Authentication is used to get a user name.

7. Run the app

Right-click on SpringBootApplication class(SpringSecurityInMemoryAuthenticationExampleApplication) then click on Run as Java Application.
Testing REST API using Postman
Get Type: http://localhost:8899/user

spring_security_in_memory_authentication_in_spring_Boot

Click on the Authorization menu then select Basic Auth after that enter username and password.

If we don’t pass the username and password then we will get a 401 status response from this API.

8. Conclusion

In this example, we learnt how to use Rest API using Spring Security In Memory Authentication in Spring Boot Application.

Leave a Comment