JWT "invalid_grant" in Signature in Google OAuth2
<p>I am writing some code to try to get a token to use from Google in OAuth2.  This is for a service account, so the instructions are here:</p>

<p><a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="noreferrer">https://developers.google.com/identity/protocols/OAuth2ServiceAccount</a></p>

<p>I keep getting this error when I post the JWT to Google:</p>

<p>{ "error": "invalid_grant", "error_description": "Invalid JWT Signature." }</p>

<p>Here is the code:</p>

<pre><code>try{        
    var nowInSeconds : Number = (Date.now() / 1000);
    nowInSeconds = Math.round(nowInSeconds);
    var fiftyNineMinutesFromNowInSeconds : Number = nowInSeconds + (59 * 60);


    var claimSet : Object = {};
    claimSet.iss   = "{{RemovedForPrivacy}}";        
    claimSet.scope = "https://www.googleapis.com/auth/plus.business.manage";
    claimSet.aud   = "https://www.googleapis.com/oauth2/v4/token";
    claimSet.iat   = nowInSeconds; 
    claimSet.exp   = fiftyNineMinutesFromNowInSeconds;

    var header : Object = {};
    header.alg = "RS256";
    header.typ = "JWT";

    /* Stringify These */
    var claimSetString = JSON.stringify(claimSet);
    var headerString = JSON.stringify(header);

    /* Base64 Encode These */
    var claimSetBaseSixtyFour = StringUtils.encodeBase64(claimSetString);
    var headerBaseSixtyFour = StringUtils.encodeBase64(headerString);

    var privateKey = "{{RemovedForPrivacy}}";

    /* Create the signature */
    var signature : Signature = Signature();
    signature =  signature.sign(headerBaseSixtyFour + "." + claimSetBaseSixtyFour, privateKey , "SHA256withRSA");

    /* Concatenate the whole JWT */
    var JWT = headerBaseSixtyFour + "." + claimSetBaseSixtyFour + "." + signature;

    /* Set Grant Type */
    var grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"

    /* Create and encode the body of the token post request */
    var assertions : String = "grant_type=" + dw.crypto.Encoding.toURI(grantType) + "&amp;assertion=" + dw.crypto.Encoding.toURI(JWT);

    /* Connect to Google And Ask for Token */
    /* TODO Upload Certs? */
    var httpClient : HTTPClient = new HTTPClient();
    httpClient.setRequestHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8");
    httpClient.timeout = 30000;
    httpClient.open('POST', "https://www.googleapis.com/oauth2/v4/token");
    httpClient.send(assertions);

    if (httpClient.statusCode == 200) {
       //nothing
    } else {
       pdict.errorMessage = httpClient.errorText;
    }  

}
catch(e){
    Logger.error("The error with the OAuth Token Generator is --&gt; " + e);
}
</code></pre>

<p>Does anyone know why the JWT is failing?</p>

<p>Thanks so much!
Brad</p>