对于最新的稳定版本,请使用 Spring Security 7.0.4spring-doc.cadn.net.cn

密码清除

成功认证后,出于安全最佳实践,应从内存中清除凭据,以防止其在潜在的内存转储攻击中被泄露。 Spring Security 中的 ProviderManager 通过 eraseCredentials 方法支持这一实践,该方法应在认证过程完成后调用。spring-doc.cadn.net.cn

最佳实践

  • 立即擦除:凭证在不再需要后应立即擦除,以尽量缩短凭证在内存中暴露的时间窗口。spring-doc.cadn.net.cn

  • 自动清除:通过将 ProviderManager 设置为 eraseCredentialsAfterAuthentication(默认值),配置 true 在身份验证后自动清除凭据。spring-doc.cadn.net.cn

  • 自定义擦除策略:如果默认的擦除行为无法满足特定的安全需求,请在自定义的 AuthenticationManager 实现中实现自定义擦除策略。spring-doc.cadn.net.cn

风险评估

未能正确清除凭证可能会导致多种风险:spring-doc.cadn.net.cn

  • 内存访问攻击:攻击者可以通过缓冲区溢出攻击或内存转储等漏洞,从内存中直接获取原始凭证。spring-doc.cadn.net.cn

  • 内部威胁:有权访问系统的恶意内部人员可能会从应用程序内存中提取凭证。spring-doc.cadn.net.cn

  • 意外泄露:在多租户环境中,内存中残留的凭据可能会被意外暴露给其他租户。spring-doc.cadn.net.cn

实施

public class CustomAuthenticationManager implements AuthenticationManager {

	@Override
	public Authentication authenticate(Authentication authenticationRequest)
			throws AuthenticationException {

		Authentication authenticationResult;
		// TODO: Perform authentication checks...

		// Erase credentials post-check
		if (authenticationResult instanceof CredentialsContainer container) {
			container.eraseCredentials();
		}
	}

}

通过实施这些实践,组织可以显著增强其身份验证系统的安全性,确保凭据不会在系统内存中暴露。spring-doc.cadn.net.cn