【发布时间】:2012-01-18 01:31:25
【问题描述】:
我刚刚为我的新 grails 项目添加了注册功能。为了测试它,我通过提供电子邮件和密码进行了注册。在将密码保存到数据库之前,我正在使用 bcrypt 算法对密码进行哈希处理。
但是,当我尝试使用注册时提供的相同电子邮件和密码登录时,登录失败。我调试了应用程序,发现当我尝试与数据库中已经散列的散列值进行比较时,为相同密码生成的散列值不同,因此登录失败(Registration.findByEmailAndPassword(params.email,hashPassd ) 在 LoginController.groovy 中返回 null)。
这是我的域类 Registration.groovy:
class Registration {
transient springSecurityService
String fullName
String password
String email
static constraints = {
fullName(blank:false)
password(blank:false, password:true)
email(blank:false, email:true, unique:true)
}
def beforeInsert = {
encodePassword()
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
这是我的 LoginController.groovy:
class LoginController {
/**
* Dependency injection for the springSecurityService.
*/
def springSecurityService
def index = {
if (springSecurityService.isLoggedIn()) {
render(view: "../homepage")
}
else {
render(view: "../index")
}
}
/**
* Show the login page.
*/
def handleLogin = {
if (springSecurityService.isLoggedIn()) {
render(view: "../homepage")
return
}
def hashPassd = springSecurityService.encodePassword(params.password)
// Find the username
def user = Registration.findByEmailAndPassword(params.email,hashPassd)
if (!user) {
flash.message = "User not found for email: ${params.email}"
render(view: "../index")
return
} else {
session.user = user
render(view: "../homepage")
}
}
}
这是我的 Config.groovy 中的一个 sn-p,它告诉 grails 使用 bcrypt 算法对密码和密钥轮数进行哈希处理:
grails.plugins.springsecurity.password.algorithm = 'bcrypt'
grails.plugins.springsecurity.password.bcrypt.logrounds = 16
【问题讨论】: