【问题标题】:Spring security UserDetailsService not workingSpring security UserDetailsS​​ervice 不起作用
【发布时间】:2025-12-04 06:40:01
【问题描述】:

好吧,我希望你能帮助我,这是我最后一次尝试。我对这个春季安全世界很陌生,我无法让它发挥作用。我尝试了很多东西,遵循了很多教程,但什么也没做。

问题正如您在标题中看到的,让自定义用户详细信息服务正常工作。它只是没有登录,似乎没有调用 customuserdetailsservice,因为 sysouts 没有显示在控制台中......

它在内存功能中具有弹簧安全性的魅力。以下是我的代码。

Spring 安全配置:

@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = CustomUserDetailsService.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    //auth.inMemoryAuthentication().withUser("ram").password("ram123").roles("ADMIN");
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());
}

@Override
public void configure(WebSecurity web) throws Exception {
  web
    .ignoring()
       .antMatchers("/bower_components/**", "/resources/**", "/img/**"); // #3
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().csrf().disable()
    .authorizeRequests()
      .antMatchers("/", "/home", "/call").permitAll() // #4
      .antMatchers("/resource", "/video").hasRole("USER") // #6
      .anyRequest().authenticated();
}

@Bean(name="passwordEncoder")
public PasswordEncoder passwordencoder(){
    return new BCryptPasswordEncoder();
}

}

CustomUserDetailsS​​ervice

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{

private UserService userService;

@Override
public UserDetails loadUserByUsername(String ssoId)
        throws UsernameNotFoundException {
    User user = userService.findByUsername(ssoId);
    System.out.println("User : "+user);
    if(user==null){
        System.out.println("User not found");
        throw new UsernameNotFoundException("Username not found");
    }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), 
             user.isEnabled(), true, true, true, getGrantedAuthorities(user));
}


private List<GrantedAuthority> getGrantedAuthorities(User user){
    List<GrantedAuthority> authorities = new ArrayList<>();

    authorities.add(new SimpleGrantedAuthority(user.getRole()));

    System.out.print("authorities :"+authorities);
    return authorities;
}
}

初始化类

@SpringBootApplication
@EnableWebSocket
public class One2OneCallApp implements WebSocketConfigurer {

@Bean
public CallHandler callHandler() {
  return new CallHandler();
}

@Bean
public UserRegistry registry() {
  return new UserRegistry();
}

@Bean
public KurentoClient kurentoClient() {
  return KurentoClient.create();
}

@Bean
public UiApplication uiApplication(){
  return new UiApplication();
}

@Bean
public CustomUserDetailsService customUserDetailsService(){
  return new CustomUserDetailsService();
}

@Bean
public SecurityConfig securityConfig(){
  return new SecurityConfig();
}

@Bean
public EncryptPassword encryptPassword(){
  return new EncryptPassword();
}

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry   registry) {
  registry.addHandler(callHandler(), "/call");
}

public static void main(String[] args) throws Exception {
  System.out.println("Iniciando");  
  new SpringApplication(One2OneCallApp.class).run(args);    
}

}

我还测试了与数据库的通信,它运行良好。我正在寻求任何帮助。抱歉英语不好。谢谢大家!

编辑:在下面回答了我自己的问题。

【问题讨论】:

  • 什么不起作用?不是注射吗?你没有访问权限吗?更详细地描述什么不起作用。转储代码并告诉这不起作用没有帮助(以及完全关闭问题的理由)。
  • 哦,对不起,我完全忘记了..它只是没有登录,似乎根本没有调用 userDetailsS​​ervice ......它抛出 401 到 angular......
  • 请您添加例外或更多详细信息。有了这些信息,我们就不清楚了。如果有,请添加您的日志和错误。
  • 能否在数据库中找到用户?
  • 这就是问题所在,没有错误,身份验证根本不起作用。它适用于内存功能。似乎没有调用 customuserdetailsservice,因为控制台中没有显示系统输出...

标签: java spring spring-security spring-boot


【解决方案1】:

SecurityConfig 类中:

@Autowired
CustomUserDetailsService customUserDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService);
}

【讨论】:

    【解决方案2】:

    改变

    @Autowired
    UserDetailsService userDetailsService;
    

    @Autowired
    CustomUserDetailsService userDetailsService;
    

    另外,在您的 web/socket 配置中导入安全配置并将组件扫描移到那里,而不是在安全上

    @ComponentScan(basePackageClasses = CustomUserDetailsService.class)
    @Import(value = { SecurityConfig.class })
    public class WebConfig extends WebMvcConfigurerAdapter { /*...*/ }
    

    【讨论】:

    • 我不知道这是否是一个问题,但我没有任何 webconfig。我试图创建一个,但我仍然得到相同的结果..
    • 在启动时检查是否有任何错误。确保正在提取服务。我用 MVC 对其进行了测试,它确实有效。
    【解决方案3】:

    您正在安全配置中设置 hasRole(" ") 并且您正在使用权限进行身份验证。

    而不是使用 .antMatchers("/resource", "/video").hasRole("USER") 使用 .antMatchers("/resource", "/video").hasAuthority("USER")

    【讨论】:

      【解决方案4】:

      我最终只为我必须做的演示而使用内置的内存认证。我认为我的问题与 Spring Boot 中的某些内容和我的应用程序中的初始化有关。

      【讨论】: