Hey guys in this post, we will discuss configuring users using InMemoryUserDetailsManager
with Example. In the previous post, we will discuss about configuring users using inMemeoryAuthentication
. This is the continuation of the previous post, please check the previous post before proceeding this post.
Table of Contents
Complete example
Let’s create a step-by-step spring boot project and add spring security to the application
Create spring boot project
There are many different ways to create a spring boot application, you can follow the below articles to create one –
>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA
Add maven dependencies
Open pom.xml
and add the following dependencies –
<?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.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>in.bushansirgur</groupId>
<artifactId>springsecurityproject</artifactId>
<version>v1</version>
<name>springsecurityproject</name>
<description>Spring security project</description>
<properties>
<java.version>1.8</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-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>
spring-boot-starter-web
dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container. spring-boot-starter-security
dependency, which will help to implement spring security.
Create a Rest controller
Create HomeController.java
inside the in.bushansirgur.springboot.controller
package and add the following content
package in.bushansirgur.springboot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@RequestMapping("/home")
public String showHomePage () {
return "displaying the home page contents";
}
@RequestMapping("/protected")
public String protectedPage () {
return "displying the protected page contents";
}
}
We have created two handler methods showHomePage()
, which is mapped to /home
, anyone can access this URI and protectedPage()
, which is mapped to /protected
, only authorized users can access this URI.
Create a configuration class
Let’s customize the spring security to deny all the URIs. Create ProjectSecurityConfig.java
inside the in.bushansirgur.springboot.config
package and add the following content.
package in.bushansirgur.springsecurity.securityConfig;
import org.springframework.context.annotation.Bean;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/home").permitAll()
.antMatchers("/protected").authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
UserDetails firstUser = User.withUsername("admin").password("12345").build();
UserDetails secondUser = User.withUsername("user").password("12345").build();
userDetailsManager.createUser(firstUser);
userDetailsManager.createUser(secondUser);
auth.userDetailsService(userDetailsManager);
}
@Bean
public PasswordEncoder passwordEncoder () {
return NoOpPasswordEncoder.getInstance();
}
}
So here we are overriding the method configure(AuthenticationManagerBuilder auth)
from WebSecurityConfigurerAdapter
class.
We are creating the object for InMemoryUserDetailsManager
, this is the implementation class for UserDetailsManager
. Then we will create user using the spring security provided built in class User
, which provides the blueprint for the user schema. On the User
object we will call withUser()
and password()
method for configuring the user credentials and we will call the build()
to return the UserDetails
.
Next, we will pass the UserDetails
to the createUser()
method of UserDetailsManager
. At last we will pass the UserDetailsManager
to the userDetailsService()
of AuthenticationManagerBuilder
.
As we discussed earlier, anytime if we want to configure users, then we must provide the password encoder. We will create a bean using @Bean
, then we will create the instance of NoOpPasswordEncoder
, saying that no encoding is used.
Note that, this is not recommended for the production ready applications. We should always encode the passwords inside the application.
Run the app
Run the application using the below maven command –
mvn spring-boot:run
Open the browser and enter the following URL –
http://localhost:8080/home
http://localhost:8080/protected
Enter the username and password which we configured inside our application. Spring security will authenticate and allow the user to see the contents.
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks i will see you in our next post.