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


在spring security中設置默認的登錄人的信息,遇到的異常信息:

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id “null
有些版本不要求這樣子做,所以就不會有該問題的發生,
我現在用的是5.0版本,強制要求提供一個,所以我們就給一個PasswordEncoder給他.
我們也可以使用Spring自帶的PasswordEncoder.為了方便起見,我們以明文形式存密碼在后台,故使用自定義PasswordEncoder

自定義passwordEncoder

public class MyPasswordEncoder implements PasswordEncoder {
 
    @Override
    public String encode(CharSequence arg0) {
        return arg0.toString();
    }
 
    @Override
    public boolean matches(CharSequence arg0, String arg1) {
        return arg1.equals(arg0.toString());
    }
 
}

應用自定義編碼器

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
 
        auth
          .inMemoryAuthentication()
          .passwordEncoder(new MyPasswordEncoder())//在此處應用自定義PasswordEncoder
          .withUser("user")
          .password("password")
          .roles("USER");
    }
}

自帶編碼器

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

別忘了在注冊用戶的地方添加編碼器加密

增加一個passwordEncoder就可以解決這種異常


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM