spring安全编码密码用bcrypt算法

时间:2015-10-23 13:29:57

标签: spring grails spring-security

我得到了一些奇怪的东西......在spring security for encode password ..

我正在尝试更改密码并将其保存到数据库..但我总是因为不同的字符串而得到错误..

像这样......

控制器中的

..

println "password  = "+oldPass
println "password 1 = "+springSecurityService.encodePassword('password')
println "password 2 = "+springSecurityService.encodePassword('password')
println "password  = "+springSecurityService.encodePassword(oldPass)

和这个ooutput

enter image description here

奇怪......每次我编码密码,我都会得到不同的结果。

我正在使用grails 3.0.5并使用bcrypt算法

grails.plugin.springsecurity.password.algorithm = 'bcrypt'

我把这行放在application.groovy

中 像这样

    // Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.akiong.security.User'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.akiong.security.UserRole'
grails.plugin.springsecurity.authority.className = 'com.akiong.security.Role'
grails.plugin.springsecurity.requestMap.className = 'com.akiong.security.RequestMap'
grails.plugin.springsecurity.securityConfigType = 'Requestmap'
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
    '/':                ['permitAll'],
    '/error':           ['permitAll'],
    '/index':           ['permitAll'],
    '/index.gsp':       ['permitAll'],
    '/shutdown':        ['permitAll'],
    '/assets/**':       ['permitAll'],
    '/**/js/**':        ['permitAll'],
    '/**/css/**':       ['permitAll'],
    '/**/images/**':    ['permitAll'],
    '/**/favicon.ico':  ['permitAll']
]
grails.plugin.springsecurity.password.algorithm = 'bcrypt'

但是当我使用bootstrap创建一个用户帐户并将其保存到数据库时.. 然后我登录...它运行正确..

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

这是一项功能bcrypt使用随机盐,因此即使是相同的密码,每次生成不同的哈希值。

如果您想检查输入的密码是否有效,则需要对Grails使用passwordEncoder.isPasswordvalid,例如:

assert passwordEncoder.isPasswordValid( 
       '$2a$10$Qb7ENpWOSsFUS2UvwT1BRefZhn55roXPgUI8fjJRm6c/nR3JIQP8a',
       'password', null)
assert passwordEncoder.isPasswordValid(
       '$2a$10$sC3.yrmNn2VLS2Aer359rei/DxoLlwFq7s6ndAHm10ncyQpIr3MfO',
       'password', null)

或普通的Spring Security passwordEncoder.matches

assert passwordEncoder.matches('password', 
       '$2a$10$Qb7ENpWOSsFUS2UvwT1BRefZhn55roXPgUI8fjJRm6c/nR3JIQP8a')
assert passwordEncoder.matches('password', 
       '$2a$10$sC3.yrmNn2VLS2Aer359rei/DxoLlwFq7s6ndAHm10ncyQpIr3MfO')

要自动装配passwordEncoder bean,只需将其定义为类的属性:

def passwordEncoder