在grails中验证密码和确认密码的最佳方法是什么?

时间:2013-11-14 15:52:42

标签: grails

我有一个包含密码和密码的域类。 password_confirm字段。 这两个单独验证。 创建这两者相同的验证的最佳实践是什么?

2 个答案:

答案 0 :(得分:4)

class User {

  String password
  String passwordConfirm


  static constraints = {
    password blank: false, nullable: false, minSize: 8, maxSize: 64, validator: {password, obj ->
      def password2 = obj.passwordConfirm
      password2 == password ? true : ['invalid.matchingpasswords']
    }
  }

}

然后将以下内容添加到messages.properties文件...

User.password.invalid.matchingpasswords=Passwords do not match

当调用user.save()或user.validate()时,将自动触发。

答案 1 :(得分:1)

我建议您使用Grails的安全插件,也许是Shiro或Spring Security Core。

在Spring Security Core的documentation中,有一个更改密码的例子:

def updatePassword = {
   String username = session['SPRING_SECURITY_LAST_USERNAME']
   if (!username) {
      flash.message = 'Sorry, an error has occurred'
      redirect controller: 'login', action: 'auth'
      return
   }
   String password = params.password
   String newPassword = params.password_new
   String newPassword2 = params.password_new_2
   if (!password || !newPassword || !newPassword2 || newPassword != newPassword2) {
      flash.message = 'Please enter your current password and a valid new password'
      render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
      return
   }

   User user = User.findByUsername(username)
   if (!passwordEncoder.isPasswordValid(user.password, password, null /*salt*/)) {
      flash.message = 'Current password is incorrect'
      render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
      return
   }

   if (passwordEncoder.isPasswordValid(user.password, newPassword, null /*salt*/)) {
      flash.message = 'Please choose a different password from your current one'
      render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
      return
   }

   user.password = newPassword
   user.passwordExpired = false
   user.save() // if you have password constraints check them here

   redirect controller: 'login', action: 'auth'
}