Wednesday, 14 August 2019

Spring Security: In-Memory Authentication


In this post, I am going to explain how to secure the apis using spring-security module. We are going to maintain an in-memory collection that store user details like username and password. We are going to allow the users who are from our database and others will get unauthorized message.

How can we achieve the above scenario?
Step 1: Extend the class 'WebSecurityConfigurerAdapter'
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter {
 
 ......
 ......

}


Step 2: Override 'userDetailsService' method.
@Override
@Bean
public UserDetailsService userDetailsService() {
 UserDetails krishnas = User.withDefaultPasswordEncoder().username("krishna").password("password123").roles("USER", "ADMIN").build();
 UserDetails rams = User.withDefaultPasswordEncoder().username("rama553").password("rama123").roles("USER").build();

 List<UserDetails> userDetails = Arrays.asList(krishnas, rams);

 return new InMemoryUserDetailsManager(userDetails);
}

As you see above snippet, I created two users krishna and rama553. krishna is given with USER and ADMIN roles, whereas rama is given with USER role.

Find the below working application.


ApplicationSecurityConfiguration.java
package com.sample.app.config;

import java.util.Arrays;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter {

 @Override
 protected void configure(HttpSecurity httpSecurity) throws Exception {
  httpSecurity.csrf().disable().authorizeRequests().antMatchers("/", "/public/*", "/css/*", "/js/*").permitAll()
    .anyRequest().authenticated().and().httpBasic();

 }

 @Override
 @Bean
 public UserDetailsService userDetailsService() {
  UserDetails krishnas = User.withDefaultPasswordEncoder().username("krishna").password("password123").roles("USER", "ADMIN").build();
  UserDetails rams = User.withDefaultPasswordEncoder().username("rama553").password("rama123").roles("USER").build();

  List<UserDetails> userDetails = Arrays.asList(krishnas, rams);

  return new InMemoryUserDetailsManager(userDetails);
 }
}


EmployeeController.java
package com.sample.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("employees/")
public class EmployeeController {

 @RequestMapping(value = "registered/count", method = RequestMethod.GET)
 public String countEmps() {
  return "Total Registered Employees : "+  1024;
 }
}


HelloWorldController.java
package com.sample.app.controller;

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

@RestController
public class HelloWorldController {
 @RequestMapping("/")
 public String homePage() {
  return "Welcome to Spring boot Application Development using Spring Security";
 }
 
 @RequestMapping("/public/aboutme")
 public String aboutMe() {
  return "I am securied by spring security module";
 }
 
}


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
 public static void main(String[] args) {
  
  SpringApplication.run(App.class, args);
 }
}


pom.xml
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>springSecurity</groupId>
 <artifactId>springSecurity</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <dependencies>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
  </dependency>

 </dependencies>
</project>


Total project structure looks like below.

Run App.java.


Open the url 'http://localhost:8080/employees/registered/count' in browser.

Enter username as ‘krishna’ and password as ‘password123’ and click on OK button.

You can see below kind of screen.

You can download complete working application from below link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment