Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Bcrypt in Spring

I am doing a local login and right know my password is stored on an h2 databse in plain text.

I want to use the Bcrypt in spring but I get this error on my application launch:

Field bCryptPasswordEncoder in com.alert.interservices.uaa.Bootstrap required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found.

To use Bcrypt I only Autowired it in my controller and encrypt the password. I did the same on my Bootstrap when filling the database:

Controller:

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

/**
 * 
 * @param user the user that is trying to access
 * @return the user if it is successfull or a bad request if not
 */
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Object authenticate(@RequestBody UserEntity user) {

    logger.debug("Begin request UAAController.authenticate()");

    String encriptedPasswd=bCryptPasswordEncoder.encode(user.getPassword().getPassword());

    UserEntity usr = authenticationService.authenticate(user.getName(), encriptedPasswd);

    (...)

Bootstrap:

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

@GetMapping("/test")
public void fillDatabse() {


    String encodedPw=bCryptPasswordEncoder.encode("test");
    Password p = new Password(encodedPw);

What Im I doing wrong?

like image 917
jose azevedo Avatar asked Apr 06 '19 10:04

jose azevedo


2 Answers

BCryptPasswordEncoder is not a bean, you can not autowire it.

use:

Password p = new Password(new BCryptPasswordEncoder().encode(encodedPw));

instead of

String encodedPw=bCryptPasswordEncoder.encode("test");
Password p = new Password(encodedPw);

and remove

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

Also make these changes in your controller

like image 130
Jens Avatar answered Sep 18 '22 23:09

Jens


You can provide a bean of BCryptPasswordEncoder by putting the following code in any of your package scanned classes annotated with @SpringBootApplication, @Configuration...

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

Also, notice that the method signature could have been

public PasswordEncoder myPasswordEncoder() (and the rest is the same)

See an example in a working project.

like image 32
lealceldeiro Avatar answered Sep 17 '22 23:09

lealceldeiro