[BUG]: 在使用 Azure 密钥库中的私钥时,Octokit JS 客户端对 API 请求进行身份验证时出现错误
作者: danielhardej创建于 2024年2月2日更新于 2025年8月26日
标签Status: Up for grabsType: Bug
The problem
When running Octokit.JS in a Azure function that is part of a GitHub app, the error Error: secretOrPrivateKey must be an asymmetric key when using RS256 gets thrown when making an API request such as:
const adminMembers = await octokit.rest.orgs.listMembers({
org: orgName,
role: 'admin',
});
This happens when storing the app private key used to authenticate Octokit in Azure key vault as a key or a secret, as an environment variable, or just as a text string.
This happens with the following set up:
- GitHub app created and subscribed to Repository, Issue, and PR events
- The app delivers a payload containing data on these events via webhook
- Payload gets sent to an Azure function app (via the function URL), created in Node.js
- The app's webhook payload successfully triggers the function's HTTP trigger
- Within the function app, an Octokit instance is created and attempts to authenticate
- API requests, such as list members or list issues, are attempted (but the errors start appearing)
### Storing as a key in Azure Key Vault
The first scenario was storing the `.pem` file (the one downloaded from the `Private keys` section of the app's settings) as a key in Azure key vault, in line with the guidance in the [documentation on Private keys](https://docs.GitHub.com/en/apps/creating-GitHub-apps/about-creating-GitHub-apps/best-practices-for-creating-a-GitHub-app#private-keys). It can be accessed by the Azure function app from the key vault without errors.
The private key is obtained in the following way, in line with the guidance in Microsoft's documentation: [Azure Key Vault Key client library for JavaScript](https://learn.microsoft.com/en-us/JavaScript/api/overview/Azure/keyvault-keys-readme?view=Azure-node-latest#authenticating-with-Azure-active-directory)
```JavaScript
const { Octokit } = require("@octokit/rest");
const { createAppAuth } = require("@octokit/auth-app");
const { DefaultAzureCredential } = require("@Azure/identity");
const { KeyClient } = require("@Azure/keyvault-keys");
const credential = new DefaultAzureCredential();
const vaultName = process.env.KEY_VAULT_NAME;
const vaultURL = `https://${vaultName}.vault.Azure.net`;
const client = new KeyClient(vaultURL, credential);
const keyName = process.env.KEY_NAME;
const keyBundle = await client.getKey(keyName);
context.log(`Key bundle: ${JSON.stringify(keyBundle.key, null, 2)}`);
const appPrivateKey =
…内容来源: octokit/octokit.js