您如何在Node.js中对GitHub App进行身份验证?

时间:2020-02-11 02:09:34

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

我创建了一个新的GitHub App,并尝试从Node进行身份验证。例如,我是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 });

这是我从上面的节点代码获取令牌后尝试的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结果:Git回购错误:HttpError:错误的凭据”

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

1 个答案:

答案 0 :(得分:3)

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应用。安装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