Spring Security报错:There is no PasswordEncoder mapped for the id "null"

博客讲述了SpringBoot集成Spring Security进行安全控制时出现报错的情况。在Spring Security 5.0前后,对密码要求不同,5.0前需纯文本密码,5中需密码存储格式。并给出两种解决方案,一是添加密码存储格式,二是针对纯文本添加特定内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot集成Spring Security进行安全控制的时候。

package com.example.boot2security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()// 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/", "/home").permitAll()//指定了/和/home不需要任何认证就可以访问,其他的路径都必须通过身份验证。
                .anyRequest()// 任何请求,登录后可以访问
                .authenticated()
                .and()
                .formLogin() //定义当需要用户登录时候,转到的登录页面
                .successForwardUrl("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }


    /**
     * 在内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER。
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("a")
                .password("a")
                .roles("USER");

    }


}

报错:

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

后发通过查询解决,解决办法如下:

在Spring Security 5.0之前,默认值PasswordEncoderNoOpPasswordEncoder需要纯文本密码。

在Spring Security 5中,默认值为DelegatingPasswordEncoder,这需要密码存储格式

 

解决方案1:添加密码存储格式,对于纯文本,添加{noop}

 @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("a")
                .password("{noop}a")
                .roles("USER");

    }

解决方案2 - User.withDefaultPasswordEncoder()forUserDetailsService

 @Bean
    public UserDetailsService userDetailsService() {

        User.UserBuilder users = User.withDefaultPasswordEncoder();
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(users.username("a").password("a").roles("USER").build());
        return manager;

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值