我们使用Spring Boot和InMemoryAuthentication来存储用户 . 在某些时候,我们需要检查特定用户的授权权限 . 我们尝试通过获取UserDetailsService bean(自动装配)并调用loadUserByUsername(用户名)来实现 . 但是,在所有尝试中都抛出UsernameNotFoundException .

为了调试原因,尝试在添加用户之后立即减少在WebSecurityConfigurerAdapter的重写configureGlobal()中执行此操作:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user1").password("1234").roles("AGENT"); 
    UserDetails ud = auth.inMemoryAuthentication().getUserDetailsService().loadUserByUsername("user1");

在设置了内存用户之后,就会抛出UsernameNotFoundException . 如上所述,在使用自动装配的userDetailsServiceBean的代码中的其他地方也会发生同样的情况 .

有关如何使上述代码段工作的任何建议吗?或者一般来说,如何获取内存中用户的凭据?

谢谢!

注意:我们没有任何自定义UserDetailsService

UPDATE

该类使用@EnableWebSecurity注释:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

参考建议的链接,尝试过其他风格:

@Autowired 
public void whatever(AuthenticationManagerBuilder auth) throws Exception {      
    auth.inMemoryAuthentication().withUser("user1").password("1234").roles("AGENT"); 
    UserDetails ud = auth.inMemoryAuthentication().getUserDetailsService().loadUserByUsername("user1");
    LOGGER.info(ud);

并且:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {      
    auth.inMemoryAuthentication().withUser("user1").password("1234").roles("AGENT"); 
    UserDetails ud = auth.inMemoryAuthentication().getUserDetailsService().loadUserByUsername("user1");
    LOGGER.info(ud);

但是,每个都一直抛出异常:

Caused by: org.springframework.security.core.userdetails.UsernameNotFoundException: user1
at org.springframework.security.provisioning.InMemoryUserDetailsManager.loadUserByUsername(InMemoryUserDetailsManager.java:122) ~[spring-security-core-4.0.3.RELEASE.jar:4.0.3.RELEASE]