[JAVA] DB authentication with Spring Security & hashing with BCrypt

Overview

Development environment

Introducing Spring Security

Select the following 4 in the dependency


Describe DB connection information in the property file

application.properties


spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/[Database name]
spring.datasource.username=[DB user name]
spring.datasource.password=[password]
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

Create a table of user information

create table USER_TABLE (
    USER_ID VARCHAR2(30 char)
  , FAMILY_NAME VARCHAR2(10 char) not null
  , FIRST_NAME VARCHAR2(10 char) not null
  , PASSWORD VARCHAR2(255) not null
  , constraint USER_TABLE_PKC primary key (USER_ID)
) ;

Data registration

The password below is a hash of "pass". I referred to this article.

INSERT INTO
    USER_TABLE
VALUES(
    '0001'
   ,'test'
   ,'Taro'
   ,'$2a$10$w0C4tFU.SLFATC1Y6Y4uy.vMYsLXhlfvgnFP4dLbRjEa6/Ag1csKS'
   );

Create Entity class

UserTable.java


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "USER_TABLE")
public class UserTable {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "USER_ID")
	private String userId;

	@Column(name = "FAMILY_NAME")
	private String familyName;

	@Column(name = "FIRST_NAME")
	private String firstName;

	@Column(name = "PASSWORD")
	private String password;

// Getter,Setter omitted


Create repository

UserTableRepository.java


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.azkz.entity.UserTable;

@Repository
public interface UserTableRepository extends JpaRepository<UserTable, String> {

	public UserTable findByUserId(String userId);

}

Create SecurityConfig

DemoSecurityConfig.java


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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {

	//Method to limit the accessible URL and specify the transition destination when login is successful
	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		httpSecurity.authorizeRequests()
				.mvcMatchers("/").permitAll() // 「/Can be accessed by anyone
				.anyRequest().authenticated() //Otherwise you need to log in
				.and()
				.formLogin()
				.defaultSuccessUrl("/success"); //When login is successful, "/Make a Get request to "success"
	}

	//Method to hash the entered password with BCrypt method
	@Bean
	protected PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}

Create UserDetailsService

DemoUserDetailsService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.azkz.entity.UserTable;
import com.azkz.repository.UserTableRepository;

@Service
public class DemoUserDetailsService implements UserDetailsService {

	@Autowired
	UserTableRepository userTableRepository;

	@Override
	public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {

		//Get data from DB based on the entered UserID
		UserTable userTable = userTableRepository.findByUserId(userId);

		//Input values (user ID, password) and instantiated DemoUserDetails class
		//Login check is performed by comparing inside Spring Security.
		return new DemoUserDetails(userTable);

	}

}

Create User Details

DemoUserDetails.java


import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;

import com.azkz.entity.UserTable;

public class DemoUserDetails extends User {

	@Autowired
	UserTable userTable;

	public DemoUserDetails(UserTable userTable) {
		// 「Collections.emptySet()Is originally a collection of authority names. This time it's empty.
		super(userTable.getUserId(), userTable.getPassword(),Collections.emptySet());
		this.userTable = userTable;
	}

	//Getter to get unique items from session information

	public String getFirstName() {
		return this.userTable.getFirstName();
	}

	public String getFamilyName() {
		return this.userTable.getFamilyName();
	}

}

Create Controller

DemoController.java


import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.azkz.security.DemoUserDetails;

@RestController
public class DemoController {

	@GetMapping("/success")
	public DemoUserDetails loginSuccess() {
		//Get logged-in user information
		DemoUserDetails demoUserDetails =
				(DemoUserDetails) SecurityContextHolder
									.getContext().getAuthentication().getPrincipal();

		return demoUserDetails;
	}
}

Screen check

Go to http: // localhost: 8080 / login

2020-03-15-19-24-53.png


Login successful

2020-03-15-19-26-25.png


Login failure

2020-03-15-19-28-26.png


At the end

Recommended Posts

DB authentication with Spring Security & hashing with BCrypt
Implemented authentication function with Spring Security ②
Implemented authentication function with Spring Security ①
Authentication / authorization with Spring Security & Thymeleaf
Achieve BASIC authentication with Spring Boot + Spring Security
Try LDAP authentication with Spring Security (Spring Boot) + OpenLDAP
Add your own authentication items with Spring Security
[Introduction to Spring Boot] Authentication function with Spring Security
Login function with Spring Security
Spring Security usage memo Authentication / authorization
Use Basic Authentication with Spring Boot
Spring Boot Tutorial Using Spring Security Authentication
Learn Spring Security authentication processing architecture
Oauth2 authentication with Spring Cloud Gateway
I get a 404 error when testing forms authentication with Spring Security
Use Spring Security JSP tags with FreeMarker
How Spring Security works with Hello World
Hash passwords with Spring Boot + Spring Security (with salt, with stretching)
Periodically update DB with Spring Batch and MyBatis
Create Spring Cloud Config Server with security with Spring Boot 2.0
Spring Security usage memo: Cooperation with Spring MVC and Boot
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Handle passwords hashed with BCryptPasswordEncoder in Spring Security in Perl
Create a simple demo site with Spring Security with Spring Boot 2.1
Try to work with Keycloak using Spring Security SAML (Spring 5)
Call your own method with PreAuthorize in Spring Security
Create API key authentication for Web API in Spring Security
A new employee tried to create an authentication / authorization function from scratch with Spring Security
Spring Security causes 403 forbidden
Self-made Validation with Spring
Spring with Kotorin ―― 1. SPRING INITIALIZR
Download with Spring Boot
Spring Boot application that specifies DB connection settings with parameters
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
Login with HttpServletRequest # login in Spring Security of Servlet 3.x environment