java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
阿新 • • 發佈:2019-01-29
在學習SpringBoot整合SpringSecurity的時候,做簡單認證的時候出現這種錯誤。
是因為,在 進行認證的時候我自定義的認證UserDetailsService 的密碼沒有進行加密,所以
才會出現這種情況。新增以下方法即可:
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
整個WebSecurityConfig的【】配置如下:
package com.snowy.security.config;
import org.springframework .context.annotation.Bean;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* Created by Snowy on 2018/6/30.
*/
@Configuration
public class LightWebSecurityConfig extends WebSecurityConfigurerAdapter{
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/login").defaultSuccessUrl("/home")
.and()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated();
}
}
我自定義的USerDetailsService是:
package com.snowy.security.security;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.net.PasswordAuthentication;
/**
* Created by Snowy on 2018/6/30.
*/
@Component
public class LightUserDetailsService implements UserDetailsService{
@Autowired
private PasswordEncoder passwordEncoder;
private Logger logger = LoggerFactory.getLogger(LightUserDetailsService.class);
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
logger.info("使用者名稱是:"+s);
return new User(s,passwordEncoder.encode("123456"),true,true,true,true,AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
當然,如果你有自己的加密方法,那麼就在LightWebSecurityConfig 中
@Bean中
return 出來的加密方法,是你自己的就行。