【问题标题】:How do you authenticate a GitHub App in Node.js?如何在 Node.js 中验证 GitHub 应用程序?
【发布时间】:2020-05-26 09:34:11
【问题描述】:

我创建了一个新的 GitHub 应用程序,我正在尝试从 Node.js 进行身份验证。我是 GitHub 应用程序的新手,例如,我不知道“installationId”应该是什么。是 App ID 吗?

我使用私钥成功获取了令牌,但是当我尝试使用 API 时,我从 Node 和 curl 中都收到了错误。

import { createAppAuth } from '@octokit/auth-app';
import { request } from '@octokit/request';

const privateKey = fs.readFileSync(__dirname + 'file.pem');
const auth = createAppAuth({
 id: 1,
 privateKey,
 installationId: 12345,
 clientId: 'xxx.xxxxxx',
 clientSecret: 'xxxxxx',
});

const appAuthentication = await auth({ type: 'app' });
console.log(`Git repo token: ` + appAuthentication.token);

const result = await request('GET /orgs/:org/repos', {
      headers: {
                 authorization: 'token ' + appAuthentication.token,
               },
               org: 'orgname',
               type: 'public',
      });
return res.status(200).json({ message: 'Git result: ' + result });

这是我从上面的 Node 代码中获取令牌后尝试的 curl 示例。

curl -i -X POST -H "Authorization: Bearer xxxxxxxxxx" -H "Accept: application/vnd.github.machine-man-preview+json" https://api.github.com/app

Node 中的结果:“Git result: Git repo error: HttpError: Bad credentials”

导致卷曲: { "message": "未找到集成", "documentation_url": "https://developer.github.com/v3" }

【问题讨论】:

标签: node.js github-api github-app octokit-js


【解决方案1】:

JSON Web Token (JWT) 身份验证只能用于 GitHub 的 REST API 的少数端点。主要是https://developer.github.com/v3/apps/上列出的那些

对于所有其他人,您需要一个安装访问令牌。

你可以试试这个吗?

const { token } = await auth({ type: "installation" });
const result = await request("GET /orgs/:org/repos", {
  headers: {
    authorization: "token " + token
  },
  org: "orgname",
  type: "public"
});

请注意,installationId 选项必须设置为有效的安装 ID。当您在 github.com 上安装 GitHub 应用程序时,您会获得安装 ID。例如,您可以在您的帐户或您拥有管理员访问权限的任何组织上安装在 https://github.com/apps/wip 的 WIP 应用程序。安装 URL 如下所示:

https://github.com/settings/installations/90210

在上面的例子中,安装ID是90210

为了简化您的代码,您可以使用auth.hook 功能,在这种情况下,将根据 URL 自动设置正确的身份验证

import { createAppAuth } from "@octokit/auth-app";
import { request } from "@octokit/request";

const privateKey = fs.readFileSync(__dirname + "file.pem");
const auth = createAppAuth({
  id: 1,
  privateKey,
  installationId: 12345
});

const requestWithAuth = request.defaults({
  request: {
    hook: auth.hook
  }
})

const result = await requestWithAuth("GET /orgs/:org/repos", {
  org: "orgname",
  type: "public"
});

更多示例请参见https://github.com/octokit/request.js/#authentication

【讨论】:

  • 谢谢!我今晚试试这个。真的非常感谢您的澄清
  • 再次感谢。一旦我了解了从何处获取安装 ID,它就可以与您修改/简化的代码一起使用。
猜你喜欢
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 2013-06-24
  • 2022-07-13
  • 1970-01-01
  • 2018-12-12
  • 2019-12-15
相关资源
最近更新 更多