2

I am thinking how to change password for user entity in my OOD Spring application.

What seems to me to be the easiest way:

  1. Ask repository for particular user account entity
  2. Encode plain password with password encoder outside of the entity
  3. Set encoded password back to entity
  4. Ask repository to save the user entity

Is this correct approach to detach password encoding to external service or should it be processed in domain object?

1
  • 1
    Maybe, the correct approach is to abstract authentication strategies of the user account where password-based auth is just one of possible many? Then this whole thing can be totally outside the domain layer. In other words, are you sure you want to have authentication as responsibility of "user entity"?
    – Roman Susi
    Commented Jul 15, 2018 at 15:31

1 Answer 1

2

It's not terribly important where exactly the password is hashed, as long as all of the hashing is kept together in one place. E.g. an entity like this would be perfectly valid:

class PasswordAuthentication {
  private User user;
  private String hashedPassword;  // includes salt

  /** Check whether the provided password is correct.
   */
  public boolean checkPassword(String plaintextPassword) {
    return secureCompare(hashedPassword, passwordHash(plaintextPassword, hashedPassword));
  }

  /** Set a new password.
   */
  public void resetPassword(String plaintextPassword) {
    hashedPassword = passwordHash(plaintextPassword, createNewSalt());
  }
}

Your point about an “external service” is correct, in so far as user authentication is often a separate bounded context from your main domain model. It is correct that e.g. an entity the represents a user profile shouldn't also do crypto.

2
  • What is a exact reason of check and reset password methods in your entity? Please could you elaborate it in more detail? Thank you.
    – jnemecz
    Commented Jul 15, 2018 at 11:44
  • @Artegon The methods are just supposed to be common password authentication operations. I've expanded them with a bit of pseudocode.
    – amon
    Commented Jul 15, 2018 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.