Spring Security In-Memory Authentication Example

By Arvind Rai, November 28, 2019
On this page, we will learn Spring Security in-memory authentication with AuthenticationManagerBuilder using Java configuration. To work with this, we have to override a method configureGlobal() of WebSecurityConfigurerAdapter class in Java configuration. The method configureGlobal() accepts an argument of AuthenticationManagerBuilder which consists a method inMemoryAuthentication() that creates a user with password and roles. In our example, we will access the user details and will display results in view logged-in by in-memory authentication. We will also access a secured method by the user. Find the complete example step-by-step.

Project Structure in Eclipse

Find the project structure in eclipse.
Spring MVC Security In-Memory Authentication Example with AuthenticationManagerBuilder Using Java Configuration

Spring Security Java Configuration

Find the configuration classes.
SecurityConfig.java
package com.concretepage.config;  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@ComponentScan("com.concretepage")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/info/**").hasAnyRole("ADMIN","USER").
		and().formLogin();
	}
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		  auth.inMemoryAuthentication().withUser("ram").password("ram123").roles("ADMIN");
		  auth.inMemoryAuthentication().withUser("ravan").password("ravan123").roles("USER");
		  auth.inMemoryAuthentication().withUser("kans").password("kans123").roles("USER");
	}
}   
AppConfig.java
package com.concretepage.config;  
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration 
@ComponentScan("com.concretepage") 
@EnableWebMvc   
@Import({ SecurityConfig.class })
public class AppConfig {  
}  

AuthenticationManagerBuilder.inMemoryAuthentication()

AuthenticationManagerBuilder builds AuthenticationManager using which in-memory, JDBC and LDAP authentication is performed. To perform in-memory authentication AuthenticationManagerBuilder provides inMemoryAuthentication() method which returns InMemoryUserDetailsManagerConfigurer using which we can add user with the method withUser. This method returns UserDetailsBuilder using which we assign password by the method password(). It again returns UserDetailsBuilder and add it now role with its method roles. In java configuration we need to extend WebSecurityConfigurerAdapter class and override a method of this class configureGlobal(). We do all the above as following.
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
	  auth.inMemoryAuthentication().withUser("ram").password("ram123").roles("ADMIN");
} 

Service class with Secured Method

Find the service class with a secured method.
IInfoService.java
package com.concretepage.service;
import org.springframework.security.access.annotation.Secured;
public interface IInfoService {
	@Secured("authenticated")
	public String getMsg();
} 
InfoService.java
package com.concretepage.service;
import org.springframework.stereotype.Service;
@Service
public class InfoService implements IInfoService {
	@Override
	public String getMsg() {
		return "Hello ";
	}
} 

Controller

Find the controller class.
package com.concretepage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.concretepage.service.IInfoService;
@Controller
@RequestMapping
public class InfoController {
	@Autowired
	private  IInfoService service;
	@RequestMapping("/info")
	public @ResponseBody String userInfo(Authentication authentication) {
		String msg = "";
		for (GrantedAuthority authority : authentication.getAuthorities()) {
		     String role = authority.getAuthority();
                     msg+=service.getMsg()+ authentication.getName()+", You have "+ role;
		}
		return msg;
	}
}	 

Output

To check the output, access the URL http://localhost:8080/cp-1/info. We will get the screen as below.
Spring MVC Security In-Memory Authentication Example with AuthenticationManagerBuilder Using Java Configuration
Enter username and password. Successfully logged in and an output will be displayed.
Spring MVC Security In-Memory Authentication Example with AuthenticationManagerBuilder Using Java Configuration

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us