Invalid_token with reason subject_token validation failure

hi,

I am working on token exchange api

  • working fine:(in postman)

I called token exchange post api of keyclaok (https:/localhost:8443/auth/realms/myrealm/protocol/openid-connect/token)
and i am passing following in body as x-www-form-urlencoded

  • client_id:
  • client_secret
  • grant_type
  • subject_token --(is access token came when I login to client1)
  • requested_token_type
  • audience:client2
    and I am getting response with exchange access token.

not working:(when calling token exchange api from angular )

when i call openid-connect/token api endpont in angular iam getting invalid token error, though same token when i check in postman i am getting result.

this is how my api looks:

getexchangetoken(){
var token = sessionStorage.getItem(“access_token”);
const body = new HttpParams()
.append(“client_id”, “client1”)
.append(“client_secret”, “3e34f688-1c98-48c6-8fc5-978f96af5390”)
.append(“grant_type”, “urn:ietf:params:oauth:grant-type:token-exchange”)
.append(“subject_token”, token)
.append(“requested_token_type”, “urn:ietf:params:oauth:token-type:refresh_token”)
.append(“audience”, “client2”);
this.http
.post(this.openidurl,body,{
headers: new HttpHeaders({
‘Access-Control-Allow-Origin’: ‘*’,
‘Content-Type’: ‘application/x-www-form-urlencoded’
}),
})
.subscribe((data) => {
return data;
});

is this the correct way of sending parameters in angular? I am not getting actually where it is failing, token is correct, it is working fine in postman

thanks in advance

Hi ravindra,
I guess you’ve already figured it out but just to mention a possible solution which gave me a hard time:

The issuer of the token has to match the URL you’re using to exchange the token. Specially working on localhost this can be a pitfall.

Examples:

Wrong:
“iss”: “http://localhost:8080/auth/realms/Keycloak-Demo”,
Token exchange URL: http://127.0.01:8080/auth/realms/Keycloak-Demo/protocol/openid-connect/token

Right:
“iss”: “http://localhost:8080/auth/realms/Keycloak-Demo”,
Token exchange URL: http://localhost:8080/auth/realms/Keycloak-Demo/protocol/openid-connect/token