Example With BCryptPasswordEncoder#
Example With BCryptPasswordEncoder#
- So, If you have just read the BCryptPasswordEncoder and others Password Encoders in Definition Of PasswordEncoder of Spring Security, so in this section we will try to apply the
BCryptPasswordEncoder
into our Spring Boot application. This example will reuse the source code in the section Custom UserDetailsService Of Spring Security and enhance it withBCryptPasswordEncoder
.
Configuration#
- So, we will comment out the old
passwordEncoder
configuration and add the new one in the classProjectSecurityConfig.class
as below.
ProjectSecurityConfig.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
- As you can see, we will create a bean of
passwordEncoder
with a new instance ofBCryptPasswordEncoder
.
Prepare Data In Database#
- So, let's use the SQL below to add a new record into the
customers
table.
1 2 3 |
|
- As you can see, the password now is a BCrypt hash string, because we are using the
BCryptPasswordEncoder
so it requires the password that contained in database must be a BCrypt hash string. If you don't know how to get an example BCrypt hash string you can go to this page to get one to do the example. - So after executing the SQL above, you will see there are two accounts in the
customers
table, the first one is the old account with plain text password (12345) and the second account is the BCrypt hash password string from raw password (12345).
1 |
|
id | password | role | |
---|---|---|---|
1 | duc.nguyen@example.com | 12345 | admin |
2 | han.do@example.com | $2a$12$V.A53NkiPnA45W44aRYi2OLwUbbu08aDoY409/SKY/bT7cdF1PpLO | admin |
Testing#
- So now, let's start your spring boot application and use postman to call api for testing. So if you use the old account with plain text password in the database, then you can see the error code 401 unauthorized has been showed.
- Because we are using the
BCryptPasswordEncoder
but the password is the plain text so the authentication will be failed and you can not access the api. - Now, let's use the account with the Bcrypt hash password in the database, then you can see the successful result as below.