我剛剛爲我的新Grails項目添加了註冊功能。爲了測試它,我通過發送郵件和密碼進行了註冊。在將密碼保存到數據庫之前,我正在使用bcrypt算法對密碼進行散列處理。Bcrypt爲相同的輸入生成不同的哈希值?
但是,當我嘗試使用登錄時輸入的電子郵件和密碼進行登錄時,登錄失敗。我調試了應用程序,發現爲相同密碼生成的散列不同於我嘗試與已經散列的數據庫進行比較,因此登錄失敗(Registration.findByEmailAndPassword(params.email,hashPassd)in 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告訴Grails的使用bcrypt算法的密碼散列片段和輪迴密鑰的數量:
grails.plugins.springsecurity.password.algorithm = 'bcrypt'
grails.plugins.springsecurity.password.bcrypt.logrounds = 16
感謝Burt。它的工作,並非常感謝關於在會話中存儲用戶的建議。我是grails的新手,並且正在使用它來開發社交如果你能提出建議,我會很感激在最佳做法等或任何有幫助的....可能是一個鏈接到您的博客(一個solipsists軍隊.....我喜歡它) – adit