Spring Security password hashing example

In this tutorial, we will create a login page using Spring security technology. We will also use BCryptPasswordEncoder recommended by Spring in order to hash the password. 

To register the data of username and the password, we will create a database userDB. The Role for the user will be handled also. Only the User role which will be used. The user with the role user should be logged in to access the home.html page.

Technologies used in this article :

  • Spring boot
  • Spring security
  • Maven
  • Intellij
  • Thymeleaf

The creation of spring using spring boot and Maven is explained here http://mkaroune.e-monsite.com/pages/spring-boot-hiberante-project/project-creation.html. You do not need to add all the dependencies as shown in the article. Only DevTools, Web, Security, JPA and Thymeleaf are needed in this example. Netherless, ws  have to add the  Thymeleaf Layout Dialect  dependency to reuse header on all Thymeleaf template

 

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>

Bellow is the structure of the project

Screen shot 2020 03 17 at 5 28 38 pm

1. Back-end:

Please follow the steps mentionned in this tutorial to create a database 

http://mkaroune.e-monsite.com/pages/spring-boot-hiberante-project/install-mysql-server.html

mysql> CREATE DATABASE userDB;

Create the entities User, Role:

Then create the repositories to interact with the DATABASE

We will create also contraints to check if the password and the confirmPassword have the same value

Now, we will configure the spring boot Security. The user can only acces the register page. Once the user is connected, he can access the home page and logout. This is is configured in the configure(HttpSecurity http) method.

BCryptPasswordEncoder is user in the passwordEncoder method to encode the password value from the login page.

The method configure(AuthenticationManagerBuilder auth) retrieve the user information from the database and checks if the user is registered and the passwords match

In the controller, we create the post method handleRegistration to create the user in the database

Run the application and check if the tables are created.

mysql> use userDB;

Bellow is the userDB structure once the project is run:

mysql>show tables;
+--------------------+
| Tables_in_userdb   |
+--------------------+
| hibernate_sequence |
| role               |
| user               |
+--------------------+
3 rows in set (0.00 sec)

Add a role to the Role table in userDB database:

mysql> insert INTO `role` VALUES (1,'USER');                       

 

2. Front-end:

 

Following are the different pages for the front end part of the application

To access to the application: http://localhost:8083

  • Register page

Screen shot 2020 03 17 at 6 06 23 pm

  • Login page:

Screen shot 2020 03 17 at 6 08 14 pm

Add a comment