在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就可以解決這種異常