Invalid token, aud did not match expected api://default

I have two springboot apps (gonna refer to them as service A, and service B).

Want to demo couple of use cases:

  1. service A makes calls to service B using a “Client Credentials Grant”. I was able to get this to work by configuring service B as a “resource server” (@EnableResourceServer). Doesn’t work unless I do that, which is fine, no problem here so far.

  2. service A makes calls to service B on behalf of a user that has authenticated with service A using his/her name/password (Authorization Code Grant). When service A is making the call to service B, service A is grabbing the “id token” from the security context and sending it as a “Bearer” token in the Authorization header set in the REST template. Service B is complaining the “aud” does not match expected audience of “api://default”. It seems “aud” in the token is set to the service A’s client id. So I assume I can’t just use that token (which is a JWT token) as a Bearer token to make calls to service B. How do I make calls to service B from service A on behalf of the logged in user?


It sounds like you might be creating the token using the org level authorization server, but then trying to validate it using the default custom authorization server.

In service A, make sure that your issuer is configured using the default custom authorization server: https://{youroktadomain}/oauth2/default

Thanks. It seems the root cause is that service A is grabbing an “id token” from the security context and sending it to service B (instead of an access token). I’ve made some changes that appear to fix the issue but still not sure that’s the optimal/correct way of doing things. Have exchanged some thoughts in the PR below:

(Pasting here for convenience, again this appears to work)

OAuth2AuthorizedClientService clientService;

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
String clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId();
OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(clientRegistrationId, oauthToken.getName());
String accessToken = client.getAccessToken().getTokenValue();
1 Like