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


Development environment

Introducing Spring Security

Select the following 4 in the dependency

Describe DB connection information in the property file


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

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.


Create Entity class


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

@Table(name = "USER_TABLE")
public class UserTable {
	@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


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

import com.azkz.entity.UserTable;

public interface UserTableRepository extends JpaRepository<UserTable, String> {

	public UserTable findByUserId(String userId);


Create SecurityConfig


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;

public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {

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

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

Create UserDetailsService

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;

public class DemoUserDetailsService implements UserDetailsService {

	UserTableRepository userTableRepository;

	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


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 {

	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


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;

public class DemoController {

	public DemoUserDetails loginSuccess() {
		//Get logged-in user information
		DemoUserDetails demoUserDetails =
				(DemoUserDetails) SecurityContextHolder

		return demoUserDetails;

Screen check

Go to http: // localhost: 8080 / login


Login successful


Login failure


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