1

我正在尝试在 Force.com 上的 Apex 中生成 JWT,但不断收到 400“错误”:“invalid_grant”。我尝试了许多变体,但无法得到有效的响应。我的clientEmailAddress 是正确的(例如##@developer.gserviceaccount.com)。我使用 openSSL 提取了我的私钥的值。我根据板上的其他帖子编写了一个 base64URL 编码的方法。任何帮助将不胜感激。

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);
}
4

1 回答 1

0

我认为方法名称是 Base64encode 但不是 base64urlencode

于 2014-12-17T14:46:02.313 回答