DDD – how and where change password for user entity

domain-driven-design

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?

Best Answer

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.