I'm trying to add some custom data for currently logged in user, so I found that I can implement my own UserDetailsService and just plug it in Spring, but it's never called, I always get Principal as just username string.
I have my implementation of UserDetailsService:
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
...
}
}
my implementation of UserDetails:
import org.springframework.security.core.userdetails.User;
public class LoggedInUser extends User {
...
}
and tried setting it in config (SecurityConfiguration) multiple ways:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthProvider;
@Autowired
private UserDetailsService userDetailServiceImpl;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
auth.userDetailsService(userDetailServiceImpl).passwordEncoder(passwordService.getPasswordEncoder());
}
...
}
or
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
auth.userDetailsService(userDetailServiceImpl).passwordEncoder(passwordService.getPasswordEncoder());
}
or
@Override
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailServiceImpl();
}
and nothing works... I tried retrieving user info multiple ways:
- in controller with @AuthenticationPrincipal where I get null
in service (I get invalid cast error):
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); (LoggedInUser) authentication.getPrincipal()
Any idea why it's not working? Is my impl class being overriden by default one somewhere else? I tried to look in the logs (logging.level.org.springframework.security=TRACE) but no luck :/ I can login, that works fine, just principal data is always only username String and not my class.