Play Framework 2 best way to store password hash of user

前端 未结 2 1679
南方客
南方客 2021-01-30 23:25

I\'ve got an add user option in my app. I\'d like to store the user pass in hash format in the database. Th password is stored in plain text format in the sample codes included

2条回答
  •  面向向阳花
    2021-01-31 00:24

    I found a much simpler solution on the web at this adress : http://rny.io/playframework/bcrypt/2013/10/22/better-password-hashing-in-play-2.html

    First download the jbcrypt-xxx.jar at this adress.

    In the libraryDependencies in build.sbt, add :

    "org.mindrot" % "jbcrypt" % "0.3m"
    

    This is the function to create a new user (located in the model class User) :

      public static User create(String userName, String password) {
        User user = new User();
        user.userName = userName;
        user.passwordHash = BCrypt.hashpw(password, BCrypt.gensalt());
        user.save();
        return user;
      }
    

    And, still in the User class, the function to authenticate :

    public static User authenticate(String userName, String password) {
        User user = User.find.where().eq("userName", userName).findUnique();
        if (user != null && BCrypt.checkpw(password, user.passwordHash)) {
          return user;
        } else {
          return null;
        }
    

    And it work !

提交回复
热议问题