在Nodejs中使用Google API进行服务validation

我试图在节点上使用YouTube数据API V3,试图提供一个经过身份validation的代理,用于执行videosearch。 由于服务将在服务器上运行,因此我创build了一个服务帐户。

这会导致下载密钥文件和以下信息:

我对JWT有一个非常基本的理解,但OAuth2页面上的服务部分build议您应该使用其中一个库来完成它,而不是自己实现它。 但是,他们不会在其支持的库中列出节点库 。

多一点挖掘,我遇到了Google API Nodejs客户端: https : //github.com/google/google-api-nodejs-client声称受Google支持,并具有OAuth2支持开箱即用。

文档是相当小的,身份validation的例子包括打印一个URL到terminal,然后在浏览器中访问它来生成一个令牌。 我对源代码进行了深入的研究,看它是否支持JWT,并且似乎内置了JWTClient 。

/** * @constructor * JWT service account credentials. * * Retrieve access token using gapitoken. * * @param {string=} email service account email address. * @param {string=} keyFile path to private key file. * @param {array=} scopes list of requested scopes. * @param {string=} subject impersonated account's email address. * */ function JWT(email, keyFile, key, scopes, subject) { JWT.super_.call(this); this.email = email; this.subject = subject; this.keyFile = keyFile; this.key = key; this.scopes = scopes; this.GAPI = GAPI; } 

这个构造函数上面的doc注释似乎是唯一的解释,我仍然不确定如何使用这个函数。

我假设:

  • email是您开发者帐户的电子邮件地址
  • keyFile是私钥的path
  • key是私钥? (如果是这样,为什么包括path?)
  • scopes是要访问的API作用域的数组
  • subject

有没有人以前使用过这个服务,或者能够对这里的差异稍微解释一下?

作为参考,这必须是服务器端,因为我需要身份validation的请求是自治的,我不能只使用未经身份validation的请求,因为我超过了我的每日补贴200请求(或类似的东西)。

我已经设法拼凑出一个可行的解决scheme,所以我将把它留在这里,以供将来有类似问题的任何人使用。

在repo中有一个JWT示例,它更详细地显示了如何使用JWT对象的构造函数。

https://github.com/google/google-api-nodejs-client/blob/master/examples/jwt.js

这是一个稍微修改的文档评论版本。

 /** * @constructor * JWT service account credentials. * * Retrieve access token using gapitoken. * * @param {string=} email service account email address from developer console. * @param {string=} keyFile absolute path to private key file. * @param {string=} key the contents of the key if you are loading it yourself (optional) * @param {array=} scopes list of requested scopes. * @param {string=} subject impersonated account's email address (optional). * */ 

完成的代码看起来像这样

 // Create the JWT client var authClient = new googleapis.auth.JWT(email, keypath, key, ['https://www.googleapis.com/auth/youtube']); // Authorize it to produce an access token authClient.authorize(function(err, tokens) { if(err) throw err; // Use discovery to get the youtube api googleapis.discover('youtube', 'v3') .execute(function(err, client) { // Create a search var search = client.youtube.search.list({ q: '<query string>', part: 'snippet', maxResults: 50 }); // Authenticate with current auth client search.authClient = authClient; // Hey presto! search.execute(function(err, results) { if(err) throw err; console.log(results.items); }); }); }); 

这个代码示例是一团糟,但它足以给你的想法。 基于你应该能够做的例子:

 client.youtube.search.list({ ... }) .withAuth(authClient) .execute(...); 

但由于某种原因, withAuth方法不存在。 我们花了一些时间去研究它做了什么,据我所知,如果你手动设置authClient属性,它就可以正常工作,如上所示。

作为一个侧面说明, err参数不是错误,但是POJO并且像上面那样抛出它们实际上并不工作。 除非你很高兴看到[Object object]作为你的debugging信息。

希望图书馆尽快得到一些正确的文件资料,这样的问题将会被解决。