The question is: I have an Auth server(spring security) and a Resource server,The Resource server can't get principal user correctly.
Spring Boot Version: 2.0.7 Spring Cloud Version: Finchley.SR2
Firstly, I go to get access token from Auth-server, and It is the success. Then, I use the token to post the Resource-server, and the controller of Resource-server can get a principal. However, the principal is a string, not a UserDetails Object.
Auth Server websecurity config like this:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MaliUserDetailsService maliUserDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(maliUserDetailsService).passwordEncoder(passwordEncoder());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Auth Server UserDetailsService:
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return user;
}
Resouce Server Controller:
@GetMapping("/test")
public String test(Authentication authentication) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
return "hello " + userDetails.getUsername();
}
When I post to resource server, it cast a exception:
java.lang.ClassCastException: class java.lang.String cannot be cast to class org.springframework.security.core.userdetails.UserDetails (java.lang.String is in module java.base of loader 'bootstrap'; org.springframework.security.core.userdetails.UserDetails is in unnamed module of loader 'app')
=============== Then I tried to change to controller code like this:
@GetMapping("/test")
public String test(Authentication authentication) {
return "hello " + authentication.getPrincipal().toString();
}
The result is "hello admin". (admin is my username)

Why the principal in the controller is a string instead of UserDetails Object? How to solve it.
