Spring In-Memory Authentication

Spring provides security frameworks to make our spring applications as secured. In this blog, I have posted the sample code for spring in-memory authentication, along with default login page.

Here my requirement is, add the login page but I don’t want to design a custom login page using HTML and CSS. And after I entered my valid username and password get the list of students in the JSON response. So first I need to add the spring security maven dependency in my pom.xml. Then I need to add the Spring security configuration class. If you want to know DAO authentication, please refer https://samplecoder.com/spring-dao-authentication/

What is authentication?

Authentication is an action or function, that enables the access to the user and controls the user access based on their roles.

Spring Security

Spring provides a security framework, that will take care of authentication and authorization. So we can easily implement it in your spring application, you don not need to put any effort to create the security layer for your application. And it can be customizable, so you can customize it, if you want.

Types Of Authentication

  • In_memory authentication
  • DAO Authentication
  • OAuth

pom.xml

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

SecurityConfiguration.java

package com.samplecoder.emo.config;

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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
	
	@Bean
	public BCryptPasswordEncoder passwordEncoder() {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		System.out.println("admin  : "+passwordEncoder.encode("admin"));
		System.out.println("user1  : "+passwordEncoder.encode("user1"));
		System.out.println("user2  : "+passwordEncoder.encode("user2"));
		return passwordEncoder;
	}
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("admin").password("$2a$10$7F3YaFnsPQIjbeVLvarwqe3/J6Gdn.fSCpPbhYfzNhuAb/fFo6xxa").roles("ADMIN");
		auth.inMemoryAuthentication().withUser("user1").password("$2a$10$uXzJvWQoZORrajgTOAKdeu0SOFJs46pS/TGB3MpCPwATaXLAheOU2").roles("USER");
		auth.inMemoryAuthentication().withUser("user2").password("$2a$10$Wd9y/A2dFSLmkbQB.3g5iuoSrKcAHKJnpU8zuC61LkvwJAinYlGmK").roles("USER");
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.cors().and().csrf().disable();
		http.authorizeRequests().antMatchers("/login").permitAll()
		.anyRequest().authenticated()
		.and().formLogin().defaultSuccessUrl("/api/student/list", true)
		.and().sessionManagement().sessionFixation().migrateSession();
	}
	
}

StudentController.java

package com.samplecoder.emo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.samplecoder.emo.entity.Student;
import com.samplecoder.emo.exceptions.StudentNotFoundException;
import com.samplecoder.emo.repository.StudentRepository;
import com.samplecoder.emo.service.StudentService;

@RestController
@RequestMapping("/api/student")
public class StudentController {
	
	@Autowired
	private StudentRepository studentRepository;
	

	@GetMapping("/list")
	private List<Student> list(){
		return studentRepository.findAll();
	}
}

User Credentials

UsernamePassword
adminadmin
user1user1
user2user2

Result: http://localhost:8080/

Spring In-Memory Authentication Bad Credential
Invalid User Credential
Success Login
Login Success

Logout: http://localhost:8080/logout

Logout
Logout Success Page

One Comment on “Spring In-Memory Authentication”

Comments are closed.