Search code examples
springkotlinencryptionencodingpasswords

Spring BCryptPasswordEncoder not matching passwords


So I have done this already multiple times in other projects but somehow I'm running into a wall and am just scratching my head why the following is not working:

I have a very simple create account function:

@Service
class AccountService {
  @Autowired
  lateinit var passwordEncoder: PasswordEncoder

...

  fun saveAccount(account: Account): Account {
      val encrypted = passwordEncoder.encode(account.password)
      logger.info("Saving account: $account")
      return accountRepo.save(account.copy(password = encrypted).withRoles(account.roles))
  }

The bean is in the SecurityConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
internal class WebSecurityConfig : WebSecurityConfigurerAdapter() {

...


  @Bean
  fun passwordEncoder(): PasswordEncoder {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder()
  }

...

}

This all works fine, a password gets encrypted and is saved to the database:

142,admin,{bcrypt}$2a$10$7dmy9MIAPnedSK3rNXc/kOP2ml9y80bVkmK82W7kJz8gCfZq.XGT2

When I try to login/match the encrypted password from the database with the password from the loginform the matching is always false:

@Autowired
lateinit var passwordEncoder: PasswordEncoder

...

fun authenticate(email: String, password: String): ResponseEntity<Any> {
  val user = userDetailsService.loadUserByUsername(email)
  return if (passwordEncoder.matches(password, user.password)) {
    val jwt: String = jwtUtil.generateToken(user)
    ResponseEntity.ok(jwt)
  }
  else{
    ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()
   }
}

When I encrypt a string and directly match it (before it has gone to the database and back as in the normal flow) it does work. So I'm thinking there must be something with the instance of the PasswordEncoder that I'm not doing correctly. Is it creating a new object everytime I use the object?


Solution

  • So with the test accounts I used, when I added roles to the account I used the save account function that creates a new encrypted password. It all worked as it should have all along.