Java Spring Hash And Password Check

I am pulling my hair out because of this. I have a simple user object like this

@Entity
public class User {
  private static final PasswordEncoder pwEncoder = new BCryptPasswordEncoder();

  @Id 
  @GeneratedValue 
  private long id;

  @NotNull(message = "FIELD_IS_NULL")
  @NotEmpty(message = "FIELD_IS_REQUIRED")
  @Length(min = 3, message = "FIELD_MUST_HAVE_AT_LEAST_3_CHARACTERS")
  private String username;

  @NotNull(message = "FIELD_IS_NULL")
  @NotEmpty(message = "FIELD_IS_REQUIRED")
  @Length(min = 6, message = "FIELD_MUST_HAVE_AT_LEAST_6_CHARACTERS")
  @Pattern(regexp = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,128}$", message="PW_MIN_6_MAX_128_1_UPPER_1_LOWER_1_NUMERIC")
  private String password;

  public User(String username, String password){
    this.username = username;
    this.password = pwEncoder.encode(password);
  }

  /* getters and setters */
}

This works fine except that password hashing occurs before any verification, which means that the hashed password is verified instead of unashged.

I use the PagingAndSortingRepositoryrepository for all my needs, and I would really like to avoid the implementation of the controller just for this case.

I feel like I am missing something really big ...

+4
source share
1 answer

If you use this constructor

public User(String username, String password){
    this.username = username;
    this.password = pwEncoder.encode(password);
}

you will have a coded password instead of the original value

you can make the @PrePersist method as follows:

@PrePersist
public void prePersist(){
    password = pwEncoder.encode(password);
}
+4
source

Source: https://habr.com/ru/post/1688470/


All Articles