My service already gets JWT token in request(so I don't need to write Resource Owner or Authorization server) and by interacting with Authorization server API it validates token. Now I want to know the user name/id in controller which I am unable to achieve. I tried using Authentication and principal everything but in my case this doesn't work. Here's my code:
ResourceServerSecurity.java
@Configuration
@EnableResourceServer
public class SecurityConfig extends ResourceServerConfigurerAdapter {
@Value("${security.oauth2.resource.id}")
private String resourceId;
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().mvcMatchers("/api/v1/**").authenticated().anyRequest().permitAll();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(resourceId);
}
Controller.java -I've tried to get user name using everything but I'm getting null
@GetMapping(value = "api/v1/testStatus")
public ResponseEntity<String> testStatus(OAuth2Authentication auth, Principal principal, @AuthenticationPrincipal User user) {
System.out.println("auth:" + auth);
System.out.println(("principal:" + principal));
System.out.println(user);
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (obj instanceof UserDetails) {
String username = ((UserDetails)obj).getUsername();
} else {
String username = obj.toString();
}
return ResponseEntity.ok("Test");
}
Anybody's help would be much appreciated.