Author

Author- Ram Ranjeet Kumar

Sunday, September 17, 2023

Spring Security6 InMemory Authentication




 In this article i'm going to show you how can you write code for In-Memory authentication by using Spring Security 6.

Use the spring-boot-starter-security for the core security features in pom.xml


Here is an example of how to configure Spring Security 6 to use in-memory authentication with two users and their roles:


Here is security configuration class

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.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;

@EnableWebSecurity
@Configuration
public class SecurityConfig{

@Bean
public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth->{
auth.requestMatchers(
"/admin").hasRole("ADMIN")
.requestMatchers(
"/user").hasAnyRole("ADMIN","USER")
.anyRequest().permitAll();
})
.formLogin(
Customizer.withDefaults())
.build();
}

@Bean
public UserDetailsService userDetailsService(){
// The builder will ensure the passwords are encoded before saving in memory
User.UserBuilder users = User.withDefaultPasswordEncoder();

// This code creates a SecurityFilterChain bean that secures all endpoints with basic authentication.
// It also creates a UserDetailsService bean that returns an InMemoryUserDetailsManager with two users:
// user and admin. The user has the role USER, while the admin has both the roles USER and ADMIN.
// The passwords are encoded using the default password encoder of Spring Security.

UserDetails user = users
.username("user")
.password(
"user")
.roles(
"USER")
.build();

UserDetails admin = users
.username("admin")
.password(
"admin")
.roles(
"USER", "ADMIN")
.build();

return new InMemoryUserDetailsManager(user, admin);
}
}


Here is controller

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

@RestController
public class HomeController {
@GetMapping("/public")
public String publicPage(){
return "<h2>This is public page</h2>";
}
@GetMapping("/user")
public String userPage(){
return ("<h2>This is user page.</h2>");
}
@GetMapping("/admin")
public String adminPage(){
return ("<h2>This is admin page.</h2>");
}
}


No comments:

Post a Comment