如何访问gmail API? [英] How to access gmail API?

查看:489
本文介绍了如何访问gmail API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成我的JWT,如果我的令牌是正确的,为什么不工作?在Google Developers Console中,我启用了gmail加上youtube和其他API,在凭据中生成和下载json

  {
private_key_id :22dcf,
private_key:----- BEGIN PRIVATE KEY -----(删除)----- END PRIVATE KEY ----- \\\

client_email:vgfjjc6@developer.gserviceaccount.com,
client_id:jc6.apps.googleusercontent.com,
type:service_account
}

第一个生成令牌

  var sHead = JSON.stringify({alg:RS256,typ:JWT}); 
var iat = timeStampf();
var exp = iat + 3600;
var sPayload = JSON.stringify({
iss:client_email,
scope:scope,// gmail 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-ty

pe%3Ajwt-bearer& assertion =+ sJWS



getToken(POST,/ oauth2 / v3 / token,paramstoken,jsonData,replier);
/ *剩余请求返回200 OK
{
access_token:1bHLl5EOtu1pxz3fmmetKx9W8CV4t79M,
token_type:承载者,
expires_in:3600
} * /

接下来我测试我的令牌

 函数testToken(accessToken,replier)
{
// / gmail / v1 / users / me / messages / plus / v1 / people / me
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 ();
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();

如果我使用google +作用域并且这个请求的答案是200好的

  https://www.googleapis.com/auth/plus.me / plus / v1 / people / me 
{
kind:plus#person,
etag:\LR9iFZQGXELLHS07eQ \,
objectType:person,id:1149981343 , 显示名: , 名:{ familyName: , 给定名称: }, 形象:{ URL:https://lh3.googleusercontent.com/-XdUIqdMkCWA /AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50\",\"isDefault\":tr}},\"isPlusUser\":false,\"language\":en_US\",\"circledByCount\":0,\"verified\":false}

但是如果我尝试使用gmail



<$ p $ {error:{errors:[{domain:global,reason:failedPrecondition,message:Bad Request}],code :400,message:Bad Request}}


解决方案

<对于GMail,您正在访问特定用户的数据,因此在创建JWT时,您需要指定用户您正试图模仿,即您想要访问其邮箱的用户。



您可以在形成JWT声明时使用sub:用户的电子邮件地址参数 set

  var sPayload = JSON.stringify({
iss:client_email,
sub :USER_EMAIL_ADDRESS
scope:范围,// gmail范围https://mail.google.com/
aud:https://www.googleapis.com/oauth2/v3/token ,
exp:exp,
iat:iat
});


I generate my JWT, if my token is correct why dont work ? in Google Developers Console i enabled gmail plus youtube and other API, in credentials generate and download json

{
  "private_key_id": "22dcf",
  "private_key": "-----BEGIN PRIVATE KEY-----(remove)-----END PRIVATE KEY-----\n",
  "client_email": "vgfjjc6@developer.gserviceaccount.com",
  "client_id": "jc6.apps.googleusercontent.com",
  "type": "service_account"
} 

first generate token

 var sHead=JSON.stringify({"alg":"RS256","typ":"JWT"});    
           var iat=timeStampf();
           var exp=iat+3600;
           var sPayload=JSON.stringify({
                      "iss":client_email,
                      "scope":scope,//gmail 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-ty

pe%3Ajwt-bearer&assertion="+sJWS   



   getToken("POST","/oauth2/v3/token",paramstoken,jsonData,replier);
 /*rest petition  return 200 OK 
       {
      "access_token" : "1bHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
      "token_type" : "Bearer",
      "expires_in" : 3600
    }*/

next i test my token

function testToken(accessToken,replier)
{
 //  /gmail/v1/users/me/messages    /plus/v1/people/me
    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();
}

if i use google+ scope and this petition the answer is 200 ok

     https://www.googleapis.com/auth/plus.me /plus/v1/people/me
    {
"kind":"plus#person",
"etag":"\"LR9iFZQGXELLHS07eQ\"",
"objectType":"person","id":"1149981343","displayName":"","name":{"familyName":"","givenName":""},"image":{"url":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50","isDefault":true},"isPlusUser":false,"language":"en_US","circledByCount":0,"verified":false}

but if i try with gmail

{"error":{"errors":[{"domain":"global","reason":"failedPrecondition","message":"Bad Request"}],"code":400,"message":"Bad Request"}}

解决方案

In case of GMail, you are accessing a particular user's data, so when creating the JWT, you need to specify the user whom you are trying to impersonate, i.e. the user whose mailbox you want to access.

You can do this using the sub:"User's email address parameter" when forming the JWT Claim set

var sPayload=JSON.stringify({
                  "iss":client_email,
                  "sub":USER_EMAIL_ADDRESS
                  "scope":scope,//gmail scope  https://mail.google.com/                
                  "aud":"https://www.googleapis.com/oauth2/v3/token",
                  "exp":exp,
                  "iat":iat
                });  

这篇关于如何访问gmail API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆