如果我尝试调用 GMail API,返回以下错误:
{
"error": {
"errors": [{
"domain": "global",
"reason": "failedPrecondition",
"message": "Bad Request"
}],
"code": 400,
"message": "Bad Request"
}
}
首先我生成一个 token
var sHead = JSON.stringify({
"alg": "RS256",
"typ": "JWT"
});
var iat = timeStampf();
var exp = iat + 3600;
var sPayload = JSON.stringify({
"iss": client_email,
"sub": client_email,
"scope": "https://mail.google.com/",
"aud": "https://www.googleapis.com/oauth2/v3/token",
"exp": exp,
"iat": iat
});
var sJWS = KJUR.jws.JWS.sign("RS256", sHead, sPayload, private_key);
var paramstoken = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + sJWS
getToken("POST", "/oauth2/v3/token", paramstoken, jsonData, replier);
/*rest petition
return 200 ok {
"access_token": "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
"token_type": "Bearer",
"expires_in": 3600
}
*/
接下来我测试 token
function testToken(accessToken, replier) {
var client = vertx.createHttpClient().host(urlbase).port(443).ssl(true).maxPoolSize(10);
var request = client.request("GET", "/gmail/v1/users/me/messages", function(resp) {
console.log('server returned status code: ' + resp.statusCode());
console.log('server returned status message: ' + resp.statusMessage());
resp.bodyHandler(function(body) {
replier(JSON.parse(body.toString()));
});
});
request.headers()
.set("Content-type", contentType)
.set("Authorization", "Bearer " + accessToken);
request.end();
client.close();
}
然后我收到错误 400 错误请求作为返回。但如果我使用不同的范围,例如 Google+,我会得到 200 ok。
我认为错误是'"sub":client_email'。我尝试在 Google 控制台中添加更多 GMail,并为项目自动创建 3 封邮件,如果尝试使用其他邮件,包括为项目自动创建的邮件和我自己的 GMail(项目的 GMail 所有者),则只有来自 Json 的邮件返回失败的前提条件错误是 401 unautorized_client。
或者我是否需要其他“grant_type 使用以下字符串,根据需要进行 URL 编码:urn:ietf:params:oauth:grant-type:jwt-bearer”?
de13@appspot.gserviceaccount.com
7686@developer.gserviceaccount.com///this is de mail downloaded in json from credentials
768-compute@developer.gserviceaccount.com
(这是服务端js)
最佳答案
问题似乎与您的 OAauth 凭据有关。在 Google Developer Console -> Credentials 上,当您尝试获取新凭据时,有 3 个选项,1) Web 应用程序(这是您应该使用的那个)2) 服务帐户(我相信您正在尝试正确使用现在),3)已安装的应用程序(适用于 iOS 和 Android 应用程序)
此外,在进行身份验证时,请提及您将尝试在“离线”模式下访问服务内容,这将为您提供“刷新 token ”以在无需用户参与的情况下发出后续请求。
您之所以能够访问 Google+,是因为它的公开数据与 Gmail 相比,您在 Gmail 中尝试访问特定用户的消息(私有(private)数据)。服务帐户凭据不会让您访问用户的私有(private)数据,并且您必须在您的案例中使用 Web 应用程序凭据模拟您试图通过身份验证访问其电子邮件的用户。
希望这对您有所帮助....
关于javascript - 如何从我自己的 GMail 访问 GMail API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30991430/