2

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.

Gustavo Gabriel
  • 1,378
  • 2
  • 17
  • 28
  • what isn't working? isn't it injecting? don't you get access? Describe in more detail what isn't working. Dumping code and telling that this doesn't work isn't helpful (and reason for closing the question at all). – M. Deinum Aug 26 '16 at 13:02
  • Oh im sorry, i totally forgot..It just not logs in, It appears that userDetailsService is not being called at all...And it throws 401 to angular... – Gustavo Gabriel Aug 26 '16 at 13:07
  • May you please add exceptions or more details. With this information we are not clear. Please add your logs and errors if any. – Vinay Prajapati Aug 26 '16 at 13:08
  • Is it able to find a User in database? – Vinay Prajapati Aug 26 '16 at 13:08
  • Thats the problem, there are no errors, the authentication simply doesnt work. It works fine with the in memory feature. It appears that the customuserdetailsservice is not being called, as the sysouts are not showing in the console... – Gustavo Gabriel Aug 26 '16 at 13:11

4 Answers4

0

In SecurityConfig class:

@Autowired
CustomUserDetailsService customUserDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService);
}
Nick
  • 3,691
  • 18
  • 36
0

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 { /*...*/ }
Sully
  • 14,672
  • 5
  • 54
  • 79
  • I dont know if this is a problem or not, but I dont have any webconfig. I tried to create one but i still get the same results.. – Gustavo Gabriel Aug 26 '16 at 14:01
  • Check for any errors on startup. Make sure the Service is being picked up. I tested it with MVC and it worked. – Sully Aug 26 '16 at 14:14
0

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")

Akash
  • 91
  • 6
-8

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.

Gustavo Gabriel
  • 1,378
  • 2
  • 17
  • 28