以下是安全配置类:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
CustomUserDetailService userDetailsService;
@Bean
public DaoAuthenticationProvider authProvider() {
CustomAuthProvider authProvider = new CustomAuthProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
return authProvider;
}
@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests()
.mvcMatchers("/favicon.ico", "/signup", "/cdn.jsdelivr.net", "/cdn.jsdelivr.net/**").permitAll()
.anyRequest().authenticated().and().formLogin(form -> form.loginPage("/login").permitAll())
.authenticationManager(new ProviderManager(List.of(authProvider()))).csrf().disable().build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
这是我的DaoAuthenticationProvider:
@Service
public class CustomAuthProvider extends DaoAuthenticationProvider {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private AuthUserRepo authUserRepo;
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
logger.info("CustomAuthProvider authentication ::::: {} ", authentication);
logger.info("CustomAuthProvider authentication.getPrincipal() ::::: {} ",
authentication.getPrincipal().toString());
final String name = authentication.getName();
logger.info("CustomAuthenticationProvider ::::: " + authentication.getCredentials().toString());
final String password = authentication.getCredentials().toString();
logger.info("CustomAuthenticationProvider ::::: " + name);
if ((name == null || password == null)) {
throw new BadCredentialsException("Invalid username or password");
}
Optional<AuthUser> authUser = authUserRepo.findByEmail(name);
if (authUser.isEmpty()) {
throw new BadCredentialsException("Invalid username or password");
}
final Authentication result = super.authenticate(authentication);
return new UsernamePasswordAuthenticationToken(authUser.get(),
result.getCredentials().toString(), result.getAuthorities());
}
}
这是我的CustomUserDetailService:
@Service
public class CustomUserDetailService implements UserDetailsService {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
AuthUserRepo authUserRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
logger.info("CustomUserDetailService -> UserName :::: {}", username);
Optional<AuthUser> savedUser = authUserRepo.findByEmail(username);
if (savedUser.isEmpty()) {
throw new UsernameNotFoundException("No user found with username: " + username);
}
return new org.springframework.security.core.userdetails.User(savedUser.get().getEmail(),
savedUser.get().getPassword(), true, true, true, true, getAuthorities());
}
private Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
final List<GrantedAuthority> authorities = new ArrayList<>();
List<String> roles = Arrays.asList("Associate", "Manager");
for (String string : roles) {
authorities.add(new SimpleGrantedAuthority(string));
}
return authorities;
}
}
我不是java.lang.IllegalArgumentException:必须设置UserDetailsService。我在安全配置中设置了UserdetailService。
以下是异常堆栈跟踪:
M 16-Sept-2022 02:14:32.372 [restartedMain] ERROR [org.springframework.boot.SpringApplication:824] - Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customAuthProvider' defined in file [/Users/itadminsalesken/Downloads/spring5login/target/classes/security/spring5login/conf/CustomAuthProvider.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: A UserDetailsService must be set
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
at security.spring5login.Spring5loginApplication.main(Spring5loginApplication.java:10)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: A UserDetailsService must be set
at org.springframework.util.Assert.notNull(Assert.java:201)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.doAfterPropertiesSet(DaoAuthenticationProvider.java:85)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.afterPropertiesSet(AbstractUserDetailsAuthenticationProvider.java:119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
... 21 common frames omitted
1条答案
按热度按时间j7dteeu81#
您是否尝试使用
@Bean
初始化securityConfig类中的UserDetailsService?这可能会导致问题,因为@Configuration
bean是在@Service
bean之前创建的。