【问题标题】:Google Maps Tracks API 401 Invalid CredentialsGoogle Maps Tracks API 401 无效凭据
【发布时间】:2015-09-11 12:15:52
【问题描述】:

我确实在 https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=mytoken 检查了我的 access_token 的有效性 回复如下,

{
 "issued_to": "myservice_account_emailid",
 "audience": "myservice_account_emailid",
 "scope": "https://www.googleapis.com/auth/tracks",
 "expires_in": 1300,
 "access_type": "offline"
}

这意味着我的令牌仍然有效,但如果我使用相同的 access_token 从我的应用程序向 google 跟踪 api 发出请求,我将得到如下响应,

Response: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}

即使我在 google 开发者控制台中创建了新项目,创建了新的服务帐户,并在应用程序中使用了新的凭据,但仍然得到相同的响应。可能是什么原因?

【问题讨论】:

    标签: node.js google-maps


    【解决方案1】:

    找到我自己。

    我容易出错的代码如下,

    var jwt = new googleapis.auth.JWT(client_email, keyFile, null, scopes, null);
    
    jwt.authorize(function(jwtErr, tokens){
        if(jwtErr){
            return;
        }
        else{
            headers = {
                'content-type' : 'application/json;charset=utf-8',
                'content-length': Buffer.byteLength(data),
                'Authorization' : tokens.access_token
            };
    
            options = {
                host: 'www.googleapis.com',
                path: '/tracks/v1/entities/create',
                headers : headers,
                method : 'POST',
            };
    
            var post_req = https.request(options, function(res){
                  res.setEncoding('utf8');
                  res.on('data', function (chunk) {
                      console.log('Response: ' + chunk);
                  });
            });
            post_req.on('error', function(error_msg){
                console.log(error_msg);
            });
            post_req.write(data);
            post_req.end();
        }
    });
    

    问题出在标头对象中,'Authorization' 字段设置为仅 access.token 值,此外我们还必须指定 token_type 值。 所以标题必须如下所示。

    headers = {
                    'content-type' : 'application/json;charset=utf-8',
                    'content-length': Buffer.byteLength(data),
                    'Authorization' : tokens.token_type+' '+tokens.access_token
                };
    

    现在它解决了 401 Invalid Credentials 错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2018-11-07
      相关资源
      最近更新 更多