【问题标题】:Grails - different passwords for same salt in Spring SecurityGrails - Spring Security中相同盐的不同密码
【发布时间】:2013-06-23 10:58:52
【问题描述】:

我的网络应用正在使用 Spring Security 插件进行身份验证和授权。我正在构建某种 API,我需要在其中验证用户密码。

Spring Security 配置为使用 BCrypt 和 5 个 logrounds 和 username 属性作为盐:

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 是带有我的参数的命令对象。问题是,在每个请求中,使用springSecurityService 编码的密码与数据库中的用户密码不同,而且永远不会相同。我也尝试在encodePassword 调用中使用常量值,如下所示: springSecurityService.encodePassword('foo', 'bar') 和结果是一样的:每个请求的编码密码都是不同的。这样我就无法验证用户密码并从数据库中获取有效的用户实例。

有什么办法解决这个问题吗?

【问题讨论】:

    标签: grails spring-security passwords salt


    【解决方案1】:

    bcrypt 每次生成一个 uniq salt,并将其包含在结果哈希中。因为它springSecurityService.encodePasswod 只是忽略第二个参数,reflectionSaltSourceProperty 选项也是如此(see sources)。因此,每次您都会为相同的输入数据获得不同的哈希值。

    您可以使用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
    

    【讨论】:

    • 谢谢。如果在您自己的代码中显式地使用 spring security core 插件进行密码检查,并且如果没有覆盖密码散列编码器,那么这是必不可少的信息。 BCrypt 是插件中的默认设置,即使文档鼓励用户这样做,也不会使用外部盐。
    猜你喜欢
    • 2011-12-06
    • 1970-01-01
    • 2019-05-08
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多