1

I am trying to generate a JWT in Apex on Force.com but keep getting a 400 "error" : "invalid_grant". I've tried numerous variations, but just can't get a valid response. My clientEmailAddress is correct (eg ##@developer.gserviceaccount.com). I extracted the value of my Private Key using openSSL. I wrote a method to base64URL encode based on other posts on the board. Any help would be greatly appreciated.

public static String base64URLencode(Blob input){
    String output = encodingUtil.base64Encode(input);
    output = output.replace('+', '-');
    output = output.replace('/', '_');
    while ( output.endsWith('=')){
        output = output.subString(0,output.length()-1);
    }
    return output;
}

public static void generateJWT(){
    Long rightNow = (dateTime.now().getTime()/1000)+1;

    JSONGenerator gen = JSON.createGenerator(false);
    gen.writeStartObject();
    gen.writeStringField('iss',clientEmailAddress);
    gen.writeStringField('scope','https:\\/\\/www.googleapis.com\\/auth\\/prediction');
    gen.writeStringField('aud','https:\\/\\/accounts.google.com\\/o\\/oauth2\\/token');
    gen.writeNumberField('exp',rightNow+300);       
    gen.writeNumberField('iat',rightNow);
    String claimSet = gen.getAsString().trim();

    String header = '{"alg":"RS256","typ":"JWT"}';
    String signatureInput = base64URLencode(blob.valueOf(header))+'.'+base64URLencode(blob.valueOf(claimSet));

    Blob signature = crypto.sign('RSA', blob.valueOf(signatureInput), encodingUtil.base64decode(privatekey));

    String jwt = signatureInput+'.'+base64URLencode(signature);

    http h = new http();
    httpRequest req = new httpRequest();
    req.setHeader('Content-Type','application/x-www-form-urlencoded');
    req.setMethod('POST'); 
    req.setBody('grant_type='+encodingUtil.urlEncode('urn:ietf:params:oauth:grant-type:jwt-bearer','UTF-8')+'&assertion='+encodingUtil.urlEncode(jwt,'UTF-8'));
    req.setEndpoint('https://accounts.google.com/o/oauth2/token');
    httpResponse res = h.send(req);
}
  • Hey man!! am facing the same issue!! did you get an answer??? http://salesforce.stackexchange.com/questions/13301/connect-apex-and-google-api-using-jwt-to-retrieve-oauth-2-0-token – Sathya Jun 27 '13 at 07:24
  • I think the unfortunate answer to this question might lie [here][1]. [1]: http://salesforce.stackexchange.com/questions/13301/connect-apex-and-google-api-using-jwt-to-retrieve-oauth-2-0-token/13375#13375 – Phil Hawthorn Jun 28 '13 at 10:45

1 Answers1

0

I think the method name is Base64encode but not base64urlencode