Search code examples
node.jsgoogle-cloud-platformgoogle-oauthservice-accounts

Google Auth Token for Service account is incorrect


I have created a service account with Domain Wide Delegation

const jwt = require("jsonwebtoken");
const sa = require("./credentials-ads.json");

const authUrl = "https://www.googleapis.com/oauth2/v4/token";
const scope = "https://www.googleapis.com/auth/adwords";

const getSignedJwt = () => {
  const token = {
    iss: sa.client_email,
    iat: parseInt(Date.now() / 1000),
    exp: parseInt(Date.now() / 1000) + 60 * 60, // 60 minutes
    aud: authUrl,
    scope,
  };

  return jwt.sign(token, sa.private_key, { algorithm: "RS256" });
};

  const signedJwt = getSignedJwt();

  console.log(signedJwt);

  const google_token = await axios.post(
    'https://oauth2.googleapis.com/token',
    'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion='+signedJwt,
    {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }
);
  res.send(google_token.data);
})

the above giving the access_token as response but it is returned as follows:

{"access_token":"abcdefghijklmnopqurstuvwxyz1234567890qwertyuiopasdfghjklzxcvbnmfasdfasdfasdf........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................","expires_in":3599,"token_type":"Bearer"}

this access token is not usable for any API call

I am trying this using HTTP/HTTPS requests in Nodejs

Was expecting to receive a usable access token, but receiving an incorrect token with .............


Solution

  • For domain wide delegation you must supply the subject to delegate as. The value of this is the email address of the user on your domain which you want the service account to impersonate.

    you are probably missing sub filed.