SpringSecurity : Configure In Memory Authentication

Configure Spring Security to Authenticate user using In-Memory Authentication.

To implement inMemory authentication, all you need to do is

  • extend WebSecurityConfigurerAdapter.
  • override configure(AuthenticationManagerBuilder) method
  • add username, password and roles/authorities for authentication.
After adding the following class to your application, you will be able to login using these username password pairs.

  1. package com.ekiras.ss.config;  
  2.   
  3. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;  
  4. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;  
  5. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;  
  6.   
  7. /** 
  8.  * @author ekansh 
  9.  * @since 30/3/16 
  10.  */  
  11. @EnableWebSecurity  
  12. public class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter{  
  13.       
  14.   
  15.     @Override  
  16.     protected void configure(AuthenticationManagerBuilder auth) throws Exception {  
  17.         auth.inMemoryAuthentication()  
  18.                 .withUser("user")  
  19.                 .password("user")  
  20.                 .roles("USER");  
  21.         auth.inMemoryAuthentication()  
  22.                 .withUser("admin")  
  23.                 .password("admin")  
  24.                 .roles("ADMIN");  
  25.     }  
  26.   
  27. }  

As shown in the code above, we have configured two user-password pairs,
First, username : user , password : user and role/authorities : USER.
Second, username : admin , password : admin and role/authorities : ADMIN.

Note :: You can use any of the above pairs to login and authenticate user. First, can be used for requests that can be accessed by USER role and Second can be used to access the requests with ADMIN role.

No comments :

Post a Comment