我的web应用程序正在使用Spring Security插件进行身份验证和授权。我正在构建一种API,在这里我需要验证用户密码。
Spring Security配置为使用BCrypt和5个loground,username
属性作为salt:
grails.plugins.springsecurity.password.algorithm = 'brcypt'
grails.plugins.springsecurity.password.bcrypt.logrounds = 5
grails.plugins.springsecurity.dao.reflectionSaltSourceProperty = 'username' // password salting
现在,在我的控制器中,我想验证用户密码和登录名。为此,我调用springSecurityService.encodePassword(cmd.password, cmd.username)
其中cmd
是带有我的params的命令对象。问题是,在每个请求中,用springSecurityService
编码的密码都是不同的,而且永远不会与数据库中的用户密码相同。我还在encodePassword
调用中尝试使用常量值,如下所示:springSecurityService.encodePassword('foo', 'bar')
和结果是一样的:在每个请求上编码的密码是不同的。这样我就无法验证用户密码并从数据库中获取有效的用户实例。
有什么办法解决这个问题吗?
bcrypt
每次生成一个uniq salt,并将其包含在结果哈希中。因此,springSecurityService.encodePasswod
只是忽略了第二个参数,也忽略了reflectionSaltSourceProperty
选项(请参阅来源)。所以,每次对于相同的输入数据,您都会得到不同的散列。
您可以使用BCrypt
类来验证密码,例如:
if (BCrypt.checkpw(candidate_password, stored_hash))
System.out.println("It matches");
else
System.out.println("It does not match");
请参阅BCrypt文档:http://static.springsource.org/autorepo/docs/spring-security/3.1.x/apidocs/org/springframework/security/crypto/bcrypt/BCrypt.html
顺便说一句,当您使用Spring Security时,它已经在框架中实现了,所以您可以使用passwordEncoder
bean:
def passwrodEncoder
...
passwordEncoder.isPasswordValid(user.password, cmd.password, user.username) //user.username will be ignored