Blog Detail

  • Home
  • Spring In-Memory Authentication

Spring In-Memory Authentication

Spring provides security frameworks to make our spring applications as secured. In this blog I posted the sample code for spring security in-memory authentication with default Spring Security Login Page.

Here my requirement is add the login page but I don’t want to design custom login page using HTML and CSS. And after I entered my valid username and password get the list of students in JSON response. So first I need to add the spring security maven dependency in my pom.xml. the I need to add the Add the Spring security configuration class with my security configurations.

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/

Bad Credential
Invalid User Credential
Success Login
Login Success

Logout: http://localhost:8080/logout

Logout
Logout Success Page

1 Comment

Write a comment