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

Spring Security登录异常:配置指定凭据登录失败,返回BAD CREDENTIALS错误

问题原因与解决方案

嘿,我一眼就揪出你遇到的问题啦!

你代码里的核心问题是:在配置内存认证时,没有告诉Spring Security要使用你定义的BCryptPasswordEncoder来校验密码。

具体来说,你已经用BCryptPasswordEncoder对密码"secret"做了加密,但在auth.inMemoryAuthentication()的配置链中,没有添加.passwordEncoder(passwordEncoder)这一步。这就导致Spring Security会使用默认的密码处理逻辑——它会把你输入的明文密码直接和存储的加密字符串做对比,两者自然不匹配,所以返回了"BAD CREDENTIALS"错误。

修正后的代码

只需要在内存认证配置中补充指定密码编码器的代码即可:

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder) // 新增这一行,指定密码编码器
                .withUser("john.doe")
                .password(passwordEncoder.encode("secret"))
                .roles("USER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return passwordEncoder;
    }
}

另外提个小细节:你在设置密码时调用的passwordEncoder().encode("secret"),其实直接用成员变量passwordEncoder.encode("secret")也能正常工作,不过这不是导致本次错误的原因,核心还是缺失了密码编码器的指定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:32:42