Spring security与Hibernate,存储加密密码

标签 spring hibernate spring-security

我确信以前有人问过这个问题,但我找不到任何可以回答这个问题的内容。

对于 Spring-security,我使用密码编码器。

<beans:bean class="org.springframework.security.authentication.encoding.ShaPasswordEncoder" id="passwordEncoder"/>


    <authentication-manager>
         <authentication-provider user-service-ref='CustomUserDetailsService'>
         <password-encoder ref="passwordEncoder"/>
         </authentication-provider>
    </authentication-manager>

在我的 UserDAOImpl 中,添加用户时我有以下代码...

@Override
public void addUser(final User user) {
    user.setPassword(passwordEncoder.encodePassword(user.getPassword(), "salt"));
    sessionFactory.getCurrentSession().save(user);
}

我的密码编码正确,但总是被读取为无效,这是有道理的,因为我不知道 Spring 如何知道我的盐是“盐” - 你如何告诉 spring security 以及 Hibernate 使用同样的盐?我是否遗漏了 Spring Security 如何管理密码的一些内容?

最佳答案

推荐的方法是使用标准密码编码器,它将使用随机盐,并将该盐与消化后的密码一起存储。这样,您就不需要提供任何盐。如果您想提供自己的盐,那么您需要将 SaltSource 注入(inject) DAO validator ,如 the documentation 中所述。 (当然,在对密码进行编码以创建新用户时使用相同的源):

The StandardPasswordEncoder in the crypto package uses a random 8-byte salt, which is stored in the same field as the password.

Note

The legacy approach to handling salt was to inject a SaltSource into the DaoAuthenticationProvider, which would obtain a salt value for a particular user and pass it to the PasswordEncoder. Using a random salt and combining it with the password data field means you don't have to worry about the details of salt handling (such as where the the value is stored), as it is all done internally. So we'd strongly recommend you use this approach unless you already have a system in place which stores the salt separately.

在您的情况下,SaltSource 将始终返回“盐”。请注意,这种加盐方式是不安全的,因为所有共享通用密码的用户(是的,确实发生了)最终都会得到相同的散列密码。这意味着攻击者找到一个用户的密码也会找到共享相同密码的所有用户的密码。

关于Spring security与Hibernate,存储加密密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11376244/

相关文章:

java - 由模拟函数 Spring Boot 返回的 NPE

java - 从 Spring hibernate 开始

java - JPA hibernate : generation type sequence always inserts 0 into column

grails - 在 log4j 附加程序内的 config.groovy 中访问 session 用户

java - spring security框架中不使用ROLE_前缀的影响

java - 如何使用 X-Forwarded-* header 创建没有上下文路径的 URI?

java - 在不向客户端应用程序公开依赖项的情况下使用 Spring

java - 将 @CollectionId 分配给和 @ElementCollection

grails - grails 3 spring security-身份验证不起作用

java - 关于当中间有数据库时如何处理国际化的建议