所以我正在构建一个 github 应用程序,我希望能够作为应用程序进行身份验证,以便我可以作为该用户进行 graphql 调用。所以,我可以作为应用程序进行身份验证,并获得 JWT,但我似乎无法使用 JWT。代码如下:
const { Octokit } = require("@octokit/core");
const { createAppAuth} = require("@octokit/auth-app");
const fs = require('fs')
const auth = createAppAuth( {
appId: process.env.APP_ID,
privateKey: fs.readFileSync(__dirname + "/../" + process.env.PRIVATE_KEY_PATH, "utf-8"),
clientId: process.env.CLIENT_ID,
clientSecret: process.env.WEBHOOK_SECRET
})
// Send requests as GitHub App
async function main() {
const {token} = await auth({type: "app"})
console.log(token);
const appOctokit = new Octokit({
baseUrl: 'https://github.<company>.com/api/v3',
auth: `token ${token}`
});
const { slug } = await appOctokit.request("GET /user");
console.log("authenticated as %s", slug);
}
main().then().catch(err => {
console.log(err.message)
console.log(err.stack)
console.log("oops")
})
我最终得到一个 HttpError: Bad Credentials。
我错过了什么?
答案 0 :(得分:1)
错误凭据错误的原因是您正在尝试以应用程序身份验证 GET /user
请求。这是一个特定于用户的请求,需要 OAuth 令牌。
尝试发送 GET /app
,它应该可以工作。
如果您确实想以用户身份进行身份验证,则有两种方法可以通过 GitHub 应用程序接收 OAuth 令牌(GitHub 将这些用户到服务器的令牌称为,因为令牌由应用程序和应用程序两者授权)用户)。
有关网络流程,请参阅 https://github.com/octokit/auth-app.js/#user-authentication-web-flow。您将需要一个可以从 GitHub 接收 http 重定向的服务器。您可以使用 @octokit/app
SDK,它为该用例和其他 OAuth 相关用例导出节点中间件,以及网络钩子:https://github.com/octokit/app.js/#middlewares
有关 OAuth 设备流程,请参阅 https://github.com/octokit/auth-app.js/#user-authentication-device-flow。
如果您想使用 OAuth 设备流进行身份验证而不暴露 OAuth 客户端密钥,您可以使用专用的 OAuth 设备流身份验证策略:https://github.com/octokit/auth-oauth-device.js