Spring Security In Memory Authentication Example

This tutorial demonstrates how to configure Spring Security to use in-memory authentication. We also look into how to customize the Spring Security AuthenticationManager to use Spring Security in-memory authentication and add multiple users with different attributes, authorities, and roles.
Let's use Spring boot to quickly create and bootstrap spring applications. We configure Spring Security to use In-Memory Authentication in this spring boot application.

Tools and Technologies Used

  • Spring Boot - 2.1.0 RELEASE
  • Spring Framework - 5.1.2 RELEASE
  • Spring Security - 5.1.1 RELEASE
  • Maven 3.5
  • Eclipse IDE

Development Steps

Let's use below development steps to create this example:
  1. Creating a Spring Boot Application
  2. Project Structure
  3. Maven Dependencies - Pom.xml
  4. Spring Security In-Memory Authentication
  5. Running the Application
  6. Demo
  7. Conclusion

1. Creating a Spring Boot Application

There are many ways to create a Spring Boot application. You can refer below articles to create a Spring Boot application.

Project Structure

Following is the package or project structure for your reference - 

Maven Dependencies - Pom.xml

Make sure the following dependencies reside on the class-path:
<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>net.javaguides.springsecurity</groupId>
    <artifactId>spring-security-inmemory-authentication-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath />
        <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Spring Security In-Memory Authentication

In the following configuration class, we are using the AuthenticationManagerBuilder with the InMemoryUserDetailsManagerConfigurer to configure the Spring Security In-Memory Authentication.
package net.javaguides.springsecurity.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic().and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("ramesh").password("{noop}ramesh").roles("USER").and().withUser("admin")
            .password("{noop}admin").credentialsExpired(true).accountExpired(true).accountLocked(true)
            .authorities("WRITE_PRIVILEGES", "READ_PRIVILEGES").roles("ADMIN");
    }
}
Notice that we are using a builder pattern to create multiple users with different attributes, authorities, and roles. This automatically configures a UserDetailsService which we can use.
Note that we have added a password storage format, for plain text, add {noop}. Prior to Spring Security 5.0, the default PasswordEncoder was NoOpPasswordEncoder which required plain text passwords. In Spring Security 5, the default is DelegatingPasswordEncoder, which required Password Storage Format like {noop}.

Simple Rest Web Service

Let's create a simple rest service that is protected. We can obtain the current in-memory user by injecting the Authentication as an argument of the method.
package net.javaguides.springsecurity.controller;

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

@RestController
public class WelComeController {

    @GetMapping("/")
    public String greeting(Authentication authentication) {

        String userName = authentication.getName();

        return "Spring Security In-memory Authentication Example - Welcome " + userName;
    }
}

Running the Application

Let's run the spring boot application with following entry point:
package net.javaguides.springsecurity;

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

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

Demo

Hit this link in browser - http://localhost:8080. Below is the default login page provided by spring security. You can create your own custom login page here.
After login success, below screen will display:

Conclusion

In this tutorial, we have seen configure Spring Security to use In-Memory Authentication in spring boot application. We have added multiple users with different attributes, authorities, and roles to configuration and secured a simple rest service. We also used HTTP Basic Authentication with a stateless configuration for securing rest full web services.
Download source code from my Github repository at https://github.com/RameshMF/spring-security-tutorial.

Related Tutorials

Comments