google-oauth-jwt中文文档|google-oauth-jwt js中文教程|解析

npm npmdoc 2年前 (2021-12-31) 559次浏览

google-oauth-jwt中文文档|google-oauth-jwt js中文教程|解析

安装命令:npm i google-oauth-jwt

google-oauth-jwt

使用 Node.js 进行服务器到服务器应用程序的 Google OAuth 2.0 身份验证。

该库生成JWT令牌来为 API 建立身份,而无需最终用户参与。这是服务器端通信的首选方案。它可用于与需要访问用户数据(例如 Google Drive、Calendar 等)的 Google API 交互,而基于 URL 的回调和用户授权提示不适用于这些数据。

令牌是为从 Google API 控制台创建的服务帐户生成的。还必须通过使用唯一服务帐户电子邮件地址的传统权限分配来授予服务帐户访问资源的权限。

身份验证过程是按照此处找到的规范实施的

此包还集成了请求以无缝查询 Google RESTful API,这是可选的。request 的集成提供了令牌的自动请求,以及内置的令牌缓存。

文档

安装

npm install google-oauth-jwt

它是如何工作的?

从服务器(或任何非基于浏览器的应用程序)使用 Google API 时,身份验证是通过服务帐户执行的,服务帐户是代表您的应用程序的特殊帐户。此帐户具有可用于授予权限的唯一电子邮件地址。如果用户想让您的应用程序访问他的 Google Drive,他必须使用提供的电子邮件地址与服务帐户共享文件或文件夹。

现在服务帐户对某些用户资源具有权限,应用程序可以使用 OAuth2 查询 API。使用 OAuth2 时,使用首先通过提交 JSON Web 令牌 (JWT) 获得的令牌执行身份验证。JWT 识别用户以及他想要访问的数据范围。JWT 还使用加密密钥进行签名以防止篡改。Google 会生成密钥并仅保留公钥以进行验证。您必须确保您的应用程序的私钥安全,以便您可以签署 JWT 以保证其真实性。

应用程序请求一个令牌,该令牌可用于与有效 JWT 交换的身份验证。然后可以将生成的令牌用于多个 API 调用,直到它过期并且必须通过提交另一个 JWT 来获取新令牌。

使用 Google Developers Console 创建服务帐户

  1. Google Developers Console 中,选择您的项目或创建一个新项目。

  2. 在“API 和身份验证”下,单击“凭据”。

  3. 在“OAuth”下,单击“创建新客户端 ID”按钮。

  4. 选择“服务帐户”作为应用程序类型,然后单击“创建客户端 ID”。

  5. 新服务帐户的密钥应自动提示下载。请注意,您的密钥受密码保护。重要提示:保留密钥的安全副本,因为 Google 仅保留公钥。

  6. 将下载的密钥转换为 PEM,以便我们可以从 Node crypto模块使用它

    为此,请在终端中运行以下命令:

    openssl pkcs12 -in downloaded-key-file.p12 -out your-key-file.pem -nodes

    系统会要求您输入在第 5 步中收到的密码。

而已!您现在拥有一个带有电子邮件地址和密钥的服务帐户,您可以在 Node 应用程序中使用这些帐户。

授予对要通过 API 请求的资源的访问权限

为了使用 API 查询资源,必须向服务帐户授予访问权限。每个具有安全设置的 Google 应用程序都必须单独配置。通过使用在 API 控制台中找到的电子邮件地址为服务帐户分配权限来授予访问权限。

例如,为了列出 Google Drive 中的文件,文件夹和文件必须与服务帐户电子邮件地址共享。同样,要访问日历,必须与服务帐户共享日历。

使用“请求”查询 Google API

在此示例中,我们使用修改后的请求实例来查询 Google Drive API。request是一个功能齐全的 HTTP 客户端,可以通过使用该requestWithJWT方法使用 Google OAuth2 功能进行扩展jwt在选项中提供设置时,修改后的模块将自动请求和缓存令牌

// obtain a JWT-enabled version of request
var request = require('google-oauth-jwt').requestWithJWT();
 
request({
  url: 'https://www.googleapis.com/drive/v2/files',
  jwt: {
    // use the email address of the service account, as seen in the API console
    email: 'my-service-account@developer.gserviceaccount.com',
    // use the PEM file we generated from the downloaded key
    keyFile: 'my-service-account-key.pem',
    // specify the scopes you wish to access - each application has different scopes
    scopes: ['https://www.googleapis.com/auth/drive.readonly']
  }
}, function (err, res, body) {
    console.log(JSON.parse(body));
});

请注意,该options对象包括jwt我们用来配置 JWT 生成对象。然后将自动请求令牌并将其插入到授权标头中。它还将被缓存并重用于使用相同服务帐户和范围的后续调用。

如果要使用特定版本的request,只需将其传递给requestWithJWT方法,如下所示:

// my version of request
var request = require('request');
// my modified version of request
request = require('google-oauth-jwt').requestWithJWT(request);

手动请求令牌

如果您只想请求与 Google API 一起使用的令牌,请使用该authenticate方法。

var googleAuth = require('google-oauth-jwt');
 
googleAuth.authenticate({
  // use the email address of the service account, as seen in the API console
  email: 'my-service-account@developer.gserviceaccount.com',
  // use the PEM file we generated from the downloaded key
  keyFile: 'my-service-account-key.pem',
  // specify the scopes you wish to access
  scopes: ['https://www.googleapis.com/auth/drive.readonly']
}, function (err, token) {
  console.log(token);
});

如果要使用内置令牌缓存,请使用TokenCache该类。使用电子邮件地址和范围作为键缓存令牌。

var TokenCache = require('google-oauth-jwt').TokenCache,
    tokens = new TokenCache();
 
tokens.get({
  // use the email address of the service account, as seen in the API console
  email: 'my-service-account@developer.gserviceaccount.com',
  // use the PEM file we generated from the downloaded key
  keyFile: 'my-service-account-key.pem',
  // specify the scopes you wish to access
  scopes: ['https://www.googleapis.com/auth/drive.readonly']
}, function (err, token) {
  console.log(token);
});

UsingTokenCache将只为多个并发请求请求一个令牌get如果令牌过期,将自动发出新的令牌请求。

手动编码 JWT

也可以使用该encodeJWT方法手动编码 JWT

var googleAuth = require('google-oauth-jwt');
 
googleAuth.encodeJWT({
  // use the email address of the service account, as seen in the API console
  email: 'my-service-account@developer.gserviceaccount.com',
  // use the PEM file we generated from the downloaded key
  keyFile: 'my-service-account-key.pem',
  // specify the scopes you which to access
  scopes: ['https://www.googleapis.com/auth/drive.readonly']
}, function (err, jwt) {
  console.log(jwt);
});

指定 JWT 生成选项

可以指定以下选项以生成用于身份验证的 JWT:

var options = {
 
  // the email address of the service account (required)
  // this information is obtained via the API console
  email: 'my-service-account@developer.gserviceaccount.com',
 
  // an array of scopes uris to request access to (required)
  // different scopes are available for each application, refer to the app documentation
  // scopes are limitations applied to the API access
  scopes: [...],
 
  // the cryptographic key as a string, can be the contents of the PEM file
  // the key will be used to sign the JWT and validated by Google OAuth
  key: 'KEY_CONTENTS',
 
  // the path to the PEM file to use for the cryptographic key (ignored if 'key' is also defined)
  // the key will be used to sign the JWT and validated by Google OAuth
  keyFile: 'path/to/key.pem',
 
  // the duration of the requested token in milliseconds (optional)
  // default is 1 hour (60 * 60 * 1000), which is the maximum allowed by Google
  expiration: 3600000,
 
  // if access is being granted on behalf of someone else, specifies who is impersonating the service account
  delegationEmail: 'email_address@mycompany.com'
 
};

更多信息:https :
//developers.google.com/accounts/docs/OAuth2ServiceAccount#formingclaimset

选项用于对将发送到 Google OAuth 服务器的 JWT 进行编码,以便发出可用于对 Google API 进行身份验证的令牌。相同的选项用于authenticateTokenCache.getjwt
传递给
request选项设置

运行测试

运行单元测试google-oauth-jwt需要有效的服务帐户、其加密密钥和要测试的 URL。

要启动测试,首先使用示例文件在“test/jwt-settings.json”中配置您的帐户。确保您的测试 URL 也与请求的范围匹配。这些测试不对 API 的结果做出任何假设,因此您可以使用任何支持 OAuth2 的 API。

例如,要通过列出 Google Drive 文件来运行测试,您可以使用以下配置:

{
  "email": "my-account@developer.gserviceaccount.com",
  "scopes": ["https://www.googleapis.com/auth/drive.readonly"],
  "keyFile": "./test/key.pem",
  "test_url": "https://www.googleapis.com/drive/v2/files"
}

要运行测试:

npm test

或者

mocha -t 5000

由于某些测试多次调用 API,因此需要 5 秒超时。如果您遇到超时超时错误,您可以提高此值,因为并非所有 Google API 都可能以相同的时间响应。

调试

要打开调试,请将“google-oauth-jwt”添加到您的DEBUG变量中。调试事件包括 JWT 生成、对 OAuth 服务器的令牌请求和令牌过期TokenCache

例如,要在运行单元测试时打开调试,请使用以下命令:

DEBUG=google-oauth-jwt mocha -t 5000

兼容性

  • 使用 Node 0.10、0.12、4.2、5.5 测试

执照

麻省理工学院许可证 (MIT)

版权所有 (c) 2013, Nicolas Mercier

特此授予任何人免费获得本软件和相关文档文件(“软件”)副本的许可,不受限制地处理本软件,包括但不限于使用、复制、修改、合并的权利、发布、分发、再许可和/或销售本软件的副本,并允许向其提供本软件的人员这样做,但须符合以下条件:

上述版权声明和本许可声明应包含在本软件的所有副本或重要部分中。

该软件“按原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于适销性、特定用途的适用性和不侵权的保证。在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任承担责任,无论是在合同诉讼、侵权行为或其他方面,由软件或软件的使用或使用或其他原因引起的或与之相关的软件。

项目贡献人员列表:


极客公园 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:google-oauth-jwt中文文档|google-oauth-jwt js中文教程|解析
喜欢 (0)
.excerpt .focus {display:none}