简体   繁体   中英

Spring security UserDetailsService not working

Ok guys, I hope you can help me, this is my last attempt. I am quite new to this spring security world and I cant get this to work. I tried many things, followed many tutorials and nothing.

The problem is as you saw in the title, make a custom user details service to work. It just not logs in, It appears that the customuserdetailsservice is not being called, as the sysouts are not showing in the console...

It works as a charm with spring security in memory features. Below are my codes.

Spring Security Config:

@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();
}

}

CustomUserDetailsService

@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;
}
}

Initializer Class

@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);    
}

}

I've also tested the communication with the database and it works perfectly fine. I'm seeking any help. Sorry for bad English. Thank you all!

Edit: Answered my own question down below.

In SecurityConfig class:

@Autowired
CustomUserDetailsService customUserDetailsService;

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

Change

@Autowired
UserDetailsService userDetailsService;

to

@Autowired
CustomUserDetailsService userDetailsService;

Also, import the security config in you web/socket config and move the component scan there, not on the security

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

You are setting hasRole(" ") in security config and you are using authorities for authentication.

instead of using .antMatchers("/resource", "/video").hasRole("USER") use .antMatchers("/resource", "/video").hasAuthority("USER")

I ended up staying with the built in memory anthentication just for the presentation I had to do. I think my problem had to do with something in spring boot and the initialization in my application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM