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

bea*_*ode 2 node.js github-api github-app octokit-js

我创建了一个新的 GitHub 应用程序,我正在尝试从 Node.js 进行身份验证。例如,我是 GitHub Apps 的新手,我不知道“installationId”应该是什么。那是应用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 });
Run Code Online (Sandbox Code Playgroud)

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

curl -i -X POST -H "Authorization: Bearer xxxxxxxxxx" -H "Accept: application/vnd.github.machine-man-preview+json" https://api.github.com/app
Run Code Online (Sandbox Code Playgroud)

Node 中的结果:“Git 结果:Git repo 错误:HttpError:错误的凭据”

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

Gre*_*gor 6

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"
});
Run Code Online (Sandbox Code Playgroud)

请注意,该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"
});
Run Code Online (Sandbox Code Playgroud)

有关更多示例,请参阅https://github.com/octokit/request.js/#authentication