Spring OAuth (OAuth2): How can I get the client credentials in a Spring MVC controller?

wandi.darko picture wandi.darko · Sep 17, 2012 · Viewed 24.8k times · Source

In this snippet:

@RequestMapping(method = GET)
public List<Place> read(Principal principal) {
  principal.getName(); 
}

principal.getName() gives me the user identification but I need a way to receive the client credentials (client => the app who is using my API). How can I do this?

Answer

Shaun the Sheep picture Shaun the Sheep · Sep 18, 2012

The client identity is available from the Authentication object which you can either cast the principal to, or get directly from the thread-local security context. Something like

Authentication a = SecurityContextHolder.getContext().getAuthentication();

String clientId = ((OAuth2Authentication) a).getAuthorizationRequest().getClientId();

If you don't want to put that code directly into your controller, you can implement a separate context accessor as described in this answer and inject that into it instead.