Search code examples
node.jsexpressopenidkeycloakkeycloak-services

Keycloak - Grant validation failed. Reason: invalid token (wrong ISS)


So I'm having some issues with getting my Keycloak-Connect sample to work.

Basically I have a simple check with Keycloak on an express route On my VM

(10.10.10.54:8081) as follows.

app.get('/api*', keycloak.protect(), (req, res) => res.status(200).send({
    message: 'Hit API Backend!',
}));

My Keycloak Server is on a separate VM (for this example http://keycloak.myexternaldomain.ca/auth/)

the calls I've been making to test this out are.

RESULT=`curl --data "grant_type=password&client_secret=mysecret&client_id=account&username=myusername&password=mypassword" http://keycloak.myexternaldomain.ca/auth/realms/TEST/protocol/openid-connect/token`

This returns the proper access token everytime,

TOKEN=`echo $RESULT | sed 's/.*access_token":"//g' | sed 's/".*//g'`  

To parse token into a variable.

curl http://10.10.10.54:8081/api -H "Authorization: bearer $TOKEN"

Which still constantly returns Access Denied, I tried this in a similar example with the Keycloak-Quickstart Node Service to see if there was a more verbose error in that. What i'd receive back was

Validate grant failed
Grant validation failed. Reason: invalid token (wrong ISS)

Though if I waited a little bit it'd give me an Expired Token error so I feel like i'm on the right track.

so obviously there is something wrong from where i'm issuing the token from not matching where it's expecting? I can make a call to get the Users credentials from the keycloak server itself by cURLing to

curl --data "grant_type=password&token=$TOKEN&client_secret=secret&client_id=account&username=myaccount&password=mypassword" http://keycloak.myexternaldomain.ca/auth/realms/TEST/protocol/openid-connect/token/introspect

am I misinterpreting how I am supposed to be using Keycloak, or is this a settings issue?

Thanks in advance


Solution

  • My Issue was in my keycloak.json ... I had a different realm vs the one I was authenticating for.

    If you're ever having this issue I suggest modifying keycloak-auth-utils to give you more verbose error logging on the grant-manager.

    Specifically changing

    else if (token.content.iss !== this.realmUrl) {
          reject(new Error('invalid token (wrong ISS)'));
    }
    

    to

    else if (token.content.iss !== this.realmUrl) {
          reject(new Error('invalid token (wrong ISS) Expecting: '+this.realmUrl+' Got: '+token.content.iss);
    }
    

    helped me track down this issue myself.