Spring Security – In-Memory Authentication
Last Updated :
30 Dec, 2021
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. Some of the key features of Spring Security are:
- Comprehensive and extensible support for both Authentication and Authorization
- Protection against attacks like session fixation, clickjacking, cross-site request forgery, etc
- Servlet API integration
- Optional integration with Spring Web MVC.
Let’s first discuss the basic simple authentication of Spring Security. In Simple authentication, Spring Security provides a default user name and the password that we have to use for valid authentication.
XML
< 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 >
|
Login page of simple authentication of Spring Security:

Password:

It is very difficult to remember this password because this is a random password and Spring Security generates a random password every time when we execute the Spring Application. If we want to add a custom user name and password in the Spring application for authentication we can add it easily(using application.properties ) but if we want to make our Spring application for multiple users it is difficult to configure their credentials. So to overcome this situation when we handle multiple authentications along with their respective roles. We will use in-memory authentication in the Spring Application.
in-memory authentication is the way for handling authentication in Spring Security. In the in-memory authentication we hardcore all the user details such as roles, passwords, and the user name. We can perform validation until the Spring server is running. If the server is stopped the memory is cleared out and we cannot perform validation. This is the main drawback of in-memory authentication.
inMemoryAuthentication() is the method of AuthenticationManagerBuilder class is used to perform in-memory authentication in the Spring Security. This method is used for creating the user with respective roles and passwords. Let’s discuss how to implement inmemoryAuthentication in Spring Security.
Step by Step Implementation
Step 1: Create a Spring Boot Project
Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web,Spring Security

Step 2: Click on Generate which will download the starter project.
Project Structure:

Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:

Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.
Step 4: Now go to the src > main > java > com.gfg.Spring.boot.app and create two java files one is controller.java and the other is config.java
controller.java
Java
@RestController
public class controller {
@GetMapping ( "/delete" ) public String delete()
{
return "This is the delete request" ;
}
}
|
The above java file is used to set the controller for handling the incoming request from the client side. Now we have to configure the request for that we will use the config.java file.
config.java
This config file is extending the WebSecurityConfigureAdapter class and we override two methods configure(AuthenticationManagerBuilder auth) and configure(HttpSecurity Http) both methods are used for handling the multiple authentications on the Spring application.
- The first method is used for adding the credentials of the users with respective roles in the inMemory of SpringApplication.
- The second method is used for handling the user-defined API in the Spring application.
Java
package com.example.SpringBootApp;
import org.springframework.context.annotation.Bean;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser( "Zack" )
.password( "aayush" )
.roles( "admin_role" )
.and()
.withUser( "GFG" )
.password( "Helloword" )
.roles( "student" );
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
httpBasic()
.and()
.authorizeRequests()
.antMatchers( "/delete" ).hasRole( "admin_role" )
.antMatchers( "/details" ).hasAnyRole( "admin_role" , "student" )
.and()
.formLogin();
}
@Bean
public PasswordEncoder getPasswordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
}
|

Note: There is no default password is generated because we have already used external configuration for handling the user credentials.
Testing the API in Postman
Go to the postman and type localhost:8080/delete
Using the admin roles:

Using the student role: Try to access the details API using the student role’s user name and password.

Similar Reads
Authentication in Spring Security
In Spring Security, âauthenticationâ is the process of confirming that a user is who they say they are and that they have the right credentials to log in to a protected resource or to perform a privileged action in an application. Spring Security helps you set up different authentication methods, li
13 min read
Spring Security - Authentication Providers
Authentication in Spring Security refers to the process of verifying the identity of a user or a client application attempting to access a protected resource. In other words, it's the process of validating the user's credentials (such as username and password) to ensure that they are who they claim
14 min read
Spring Security - Form-Based Authentication
Form-Based Authentication in Spring Security provides a secure way to authenticate users using a custom login form instead of the default security prompt. It allows better control over authentication flow, user experience, and security configurations. Key Features: Customizable login and logout mech
5 min read
Spring Security - Basic Authentication
Spring Security is a framework that allows a programmer to use JEE components to set security limitations on Spring-framework-based Web applications. In a nutshell, 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 famil
8 min read
Spring Security - JDBC Authentication
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun Microsystems that provides a standard abstraction(API or Protocol) for Java applications to communicate with various databases. It provides the language with Java datab
8 min read
Spring Security - Role Based Authentication
Authentication is when anyone wants to access your Rest API they need some Authorization like a Username, Password, and token kind of. So Spring Boot Security has a Spring Boot 6.2.0 version. In the lower version Some Methods are deprecated in spring Security that's why a new thing comes into the pi
4 min read
Spring Security - Two Factor Authentication
Two-factor authentication (2FA) is a security method that requires users to provide two forms of authentication to access their accounts. These forms of authentication typically include something the user knows (such as a password or PIN) and something the user has (such as a mobile device or hardwa
10 min read
Spring Security Custom AuthenticationFailureHandler
In Java, Spring Security is a very powerful framework that can provide comprehensive security services for Java enterprise software applications. One of the essential aspects of the security is authentication and it can be users are verified before granting access to the resource. Spring Security ca
6 min read
Spring Security Annotations
There are multiple annotations supported by Spring Security. But, in this article, we will discuss about these annotations can be used in a Spring Boot project as well. These annotations play a crucial role in creating a web application in Spring Boot. The Spring Security annotations are a powerful
3 min read
Servlet - Authentication Filter
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Authentication Filter In Servlets Authentication may b
2 min read