You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security 5 Basic认证配置sha256编码器后抛出BadCredentialsException问题

问题根因

  • Spring Security 5 中{sha256}前缀对应的默认密码哈希逻辑并非对明文做单次无盐SHA256计算,而是默认自动生成随机盐值,最终存储的密码格式要求为{sha256}随机盐$哈希结果。你当前配置里直接在{sha256}后拼接明文password的无盐SHA256结果,不符合框架的密码解析匹配规则,所以抛出凭证错误异常。
  • 你用到的哈希值5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8确实是明文password的单次无盐SHA256计算结果,和框架{sha256}默认编码器的计算逻辑不兼容。

解决方案

方案1:使用框架标准API生成符合格式的密码(推荐)

直接调用Spring Security提供的密码编码器工具生成符合规则的密码串,替换配置中的密码字段即可:

import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

public class PasswordGenerator {
    public static void main(String[] args) {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        // 输出的字符串就是可以直接写入配置的符合格式的密码
        System.out.println(encoder.encode("password"));
    }
}

生成的密码格式类似如下(盐值随机生成,每次运行结果不同):

{sha256}98c10972acb6638c$2b7c18f55a6e4d9f8a7b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f

方案2:显式配置无盐SHA256编码器(仅测试用,不推荐生产使用)

如果你需要继续使用当前生成的无盐SHA256哈希值,可以手动指定密码编码器为无盐实现,修改配置如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            // 显式指定无盐SHA-256编码器
            .passwordEncoder(new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256") {
                @Override
                protected String encode(CharSequence rawPassword, Object salt) {
                    // 禁用加盐逻辑
                    return super.encode(rawPassword, null);
                }
            })
            .withUser("user")
            .password("5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8")
            .roles("ADMIN");
    }
}

注意:无盐哈希安全性极低,容易被彩虹表攻击破解,生产环境请务必使用带随机盐的编码方案。


内容的提问来源于stack exchange,提问作者hal90000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:24:10