Generate a GitHub app token on demand
2 min readDec 1, 2023
This is a simple TypeScript (for Node.js) snippet you can use to generate a token for a GitHub app.
The requirement is to have a GitHub app installed inside an organization.
Note: scroll down to know how to find the values of the various parameters of the function.
import {createAppAuth} from "@octokit/auth-app";
export interface GitHubAppToken {
token: string;
expiresAt: Date;
}
export async function generateGitHubAppToken(
appId: string,
installationId: string,
privateKey: string,
// Having the private key encoded as base64 helps
// distributing it as a secret in k8s.
// privateKeyBase64: string
): Promise<GitHubAppToken> {
// If you are passing the private key as base64
// const privateKey = Buffer.from(privateKeyBase64, 'base64').toString();
const auth = createAppAuth({
appId,
privateKey: privateKey
});
const installationAuthentication = await auth({
type: 'installation',
installationId
});
const {token, expiresAt} = installationAuthentication;
return {
token,
expiresAt: new Date(expiresAt)
};
}
You can then use the token to execute any calls to GitHub, e.g. with Axios:
const {token} = await generateGitHubAppToken(
appId,
installationId,
privateKey
)
const client = axios.create({
baseURL: 'https://api.github.com',
timeout: 60 * 1000, // 60 seconds
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28'
}
});
Note: the token will expire normally after 1 hour! This means it needs to be generated on demand, or keep track of the expiry of the previous one and generate a new one on schedule.
You can find the various parameters by:
- Going to the GitHub app settings page
- Follow this chain of links: Organization profile ->
Developer settings
->GitHub Apps
->Edit
(on the desired app) - On the page, look for the
App ID: 123456
, where123456
is theappId
parameter. - Also, towards the bottom of the page, you can find the
Private keys
section where you can generate a new private key. Once you create a new key, you will download a file, and the content of this file must be used as theprivateKey
parameter. - Then, follow these links:
Install App
->Install
(to install the app in your organization) or click on the gear icon if the app is already installed - Note the page URL, which is now similar to
https://github.com/organizations/my-organization/settings/installations/12345678
12345678
will be theinstallationId
parameter