此版本仍在开发中,尚未被视为稳定版本。如需最新稳定版本,请使用 Spring Security 7.0.4spring-doc.cadn.net.cn

UserDetails

UserDetailsUserDetailsService 返回。 DaoAuthenticationProvider 验证 UserDetails,然后返回一个 Authentication,其主体为配置的 UserDetailsService 所返回的 UserDetailsspring-doc.cadn.net.cn

凭证管理

强烈建议在存储用户凭据的类(例如那些扩展或实现了 CredentialsContainer 的类)中实现 UserDetails 接口,尤其是在用户详细信息未被缓存的应用程序中。 这种做法通过确保密码等敏感数据不会在内存中保留超过必要的时间,从而增强安全性。spring-doc.cadn.net.cn

在用户详细信息被缓存的情况下,请考虑创建一个不包含凭据的 UserDetails 副本,并在自定义的 AuthenticationProvider 中返回该副本,而不是原始对象。 这有助于防止在身份验证过程完成后,应用程序的其余部分引用包含凭据的缓存实例。spring-doc.cadn.net.cn

何时实施CredentialsContainer

未对UserDetails采用缓存机制的应用程序应特别考虑实现CredentialsContainer。 这种方法有助于降低因在内存中保留敏感信息而带来的风险,此类信息可能容易受到内存转储等攻击手段的威胁。spring-doc.cadn.net.cn

public class MyUserDetails implements UserDetails, CredentialsContainer {

    private String username;

    private String password;

    // UserDetails implementation...

    @Override
    public void eraseCredentials() {
        this.password = null; // Securely dereference the password field
    }

}

实现指南

  • 立即擦除:凭证在不再需要后应立即擦除,通常是在身份验证之后。spring-doc.cadn.net.cn

  • 自动调用:确保在身份验证流程完成后,您的身份验证框架(例如 eraseCredentials())会自动调用 AuthenticationManager 方法。spring-doc.cadn.net.cn

  • 一致性:在所有应用程序中统一应用此实践,以防止可能导致数据泄露的安全漏洞。spring-doc.cadn.net.cn

超越基础接口实现

虽然像 CredentialsContainer 这样的接口为凭据管理提供了框架,但实际的实现通常取决于具体的类及其相互交互。spring-doc.cadn.net.cn

例如,DaoAuthenticationProvider 类遵循 AuthenticationProvider 的约定,不会在其自身的 authenticate 方法中执行凭据清除操作。 相反,它依赖于 ProviderManager——Spring Security 中 AuthenticationManager 的默认实现——在认证完成后处理凭据及其他敏感数据的清除。 这种职责分离强调了这样一个原则:即 AuthenticationProvider 不应承担凭据管理的责任。spring-doc.cadn.net.cn

CredentialsContainer 集成到您的 UserDetails 实现中,符合安全最佳实践,通过缩短敏感数据在内存中的存活时间,降低数据泄露的潜在风险。spring-doc.cadn.net.cn