如何在 Node.js 中验证 GitHub 应用程序?

How do you authenticate a GitHub App in Node.js?

我创建了一个新的 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 });

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

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

节点中的结果:"Git result: Git repo error: HttpError: Bad credentials"

卷曲结果: { "message": "Integration not found", "documentation_url": "https://developer.github.com/v3" }

JSON Web 令牌 (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 应用程序。安装 URLs 看起来像这样:

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