Sub topic 11
Creating and using installation access tokens
This chapter assumes you have read the previous chapters. You should know what a GitHub App is, how it is installed on an account, and how to sign a JWT with the app's private key. You also need a terminal, environment variables, and basic comfort with REST calls.
Why installation access tokens exist
An app JWT proves that you hold the app's private key. It identifies the app itself, but it can only call a small set of endpoints, such as listing installations or creating tokens. It cannot read a repository's issues or push code.
To act inside an account, the app asks GitHub for an installation access token. This token is tied to one installation, which is one app on one user or organization account. It carries only the permissions and repositories that the installation was granted.
The usual flow has three steps:
- Sign a JWT with the private key.
- Send the JWT to GitHub to get an installation access token.
- Use the installation token for normal API calls.
Properties of an installation token
- Short-lived. The token expires after one hour. The response includes an
expires_attimestamp. - Limited by the installation. It can never exceed the permissions the app declared and the account owner approved.
- Limited by repositories. It can reach only the repositories the installation covers, which are either all repositories or a selected list.
- Not renewable. You cannot refresh it. You create a new one by signing a new JWT.
- Acts as the app. Actions appear as the app's bot account, for example
my-app[bot], not as a person.
Finding the installation ID
The token request needs an installation ID. You can get it in several ways:
- From a webhook payload. Events sent to your app include an
installationobject with anid. - From the app's settings page. The installation URL ends with the ID, for example
https://github.com/settings/installations/12345678. - From the API. Call
GET /app/installationswith the app JWT, orGET /repos/OWNER/REPO/installationto find the installation for one repository.
curl -L \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $APP_JWT" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/OWNER/REPO/installationThe response includes an id field. That value is your INSTALLATION_ID.
Creating the token with curl
Send a POST request to the installation's access_tokens endpoint. Authenticate with the JWT, not with any other token.
curl -L -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $APP_JWT" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/app/installations/$INSTALLATION_ID/access_tokensA successful response has status 201 Created. The body looks like this, shortened:
{
"token": "ghs_16C7e42F292c6912E7710c838347Ae178B4a",
"expires_at": "2026-12-04T17:31:21Z",
"permissions": {
"contents": "read",
"issues": "write"
},
"repository_selection": "selected"
}Installation tokens begin with the prefix ghs_. The permissions field shows what the token can do, and repository_selection shows whether it covers all repositories or a selected list.
Narrowing the token further
By default, the token gets every permission and repository the installation has. You can request less by sending a JSON body. This follows the principle of least privilege. If one job only needs to read a single repository, the token for that job should not reach the others.
curl -L -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $APP_JWT" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/app/installations/$INSTALLATION_ID/access_tokens \
-d '{"repositories":["REPO"],"permissions":{"contents":"read"}}'The request body can use these fields:
| Field | Meaning |
|---|---|
| `repositories` | Repository names, without the owner, that the token may access |
| `repository_ids` | The same restriction, by numeric repository ID |
| `permissions` | A map of permission names to `read`, `write`, or `admin` |
You can only reduce access this way. If you ask for a permission the installation does not have, or a repository outside the installation, GitHub returns an error, usually 422 Unprocessable Entity.
Using the token
Once you have the installation token, call the API as you would with any bearer token. The first code example in this tutorial used $GITHUB_TOKEN. Here you place the installation token in the same header.
curl -L \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $INSTALLATION_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/installation/repositoriesThe endpoint GET /installation/repositories works only with an installation token. It lists the repositories the token can reach, so it is a good first test.
Git operations over HTTPS also work. Use x-access-token as the username and the token as the password:
git clone https://x-access-token:[email protected]/OWNER/REPO.gitAvoid leaving the token in a remote URL that is saved in .git/config. Use a credential helper or remove the remote afterward.
Letting Octokit handle the exchange
Writing the JWT and token exchange by hand is useful for learning. In production, the Octokit App class does both steps and caches the token. It renews the token before it expires.
import { App } from "octokit";
import fs from "node:fs";
const app = new App({
appId: process.env.GITHUB_APP_ID,
privateKey: fs.readFileSync(process.env.GITHUB_APP_PRIVATE_KEY_PATH, "utf8"),
});
const octokit = await app.getInstallationOctokit(Number(process.env.INSTALLATION_ID));
const { data } = await octokit.request("GET /installation/repositories");
console.log(data.repositories.map((r) => r.full_name));getInstallationOctokit returns a client already authenticated as the installation. You do not handle the token yourself. If you run the call many times, the library reuses the token until it nears expiry.
Common errors
| Status | Likely cause | Fix |
|---|---|---|
| `401 Unauthorized` on the token request | JWT is expired, malformed, signed with the wrong key, or `iss` is wrong | Regenerate the JWT. Check the app ID, the key file, and the system clock. |
| `401` on a normal call | Installation token expired after one hour | Create a new token. |
| `404 Not Found` on the token request | Installation ID is wrong, or the app was uninstalled | List installations and confirm the ID. |
| `403 Forbidden` on a normal call | The app lacks the needed permission, or the installation has not accepted a permission change | Check the app's permissions. Ask the owner to approve updated permissions. |
| `404` on a repository | The repository is outside the installation, or the token was narrowed to exclude it | Check `repository_selection` and the repositories list. |
| `422` on the token request | The requested permissions or repositories exceed the installation | Request a subset of what the installation has. |
A 404 on a private repository often means "you cannot see it" rather than "it does not exist." GitHub hides the difference on purpose.
Another cause of 401 on the JWT request is clock drift. This is why the earlier JWT example backdates iat by 60 seconds. The exp claim must be no more than 10 minutes after the time GitHub receives the request.
Caching and refreshing in your own code
If you manage tokens yourself, store the token with its expires_at value and reuse it until a few minutes before expiry. Creating a new token for every request wastes calls and adds latency. A simple approach is to keep a map from installation ID to token and refresh when less than five minutes remain.
const cache = new Map();
export async function getToken(installationId, createToken) {
const cached = cache.get(installationId);
const fiveMinutes = 5 * 60 * 1000;
if (cached && new Date(cached.expiresAt).getTime() - Date.now() > fiveMinutes) {
return cached.token;
}
const { token, expires_at } = await createToken(installationId);
cache.set(installationId, { token, expiresAt: expires_at });
return token;
}Here createToken is your function that signs a JWT and calls the access_tokens endpoint. In a multi-process deployment, each process holds its own cache. That is acceptable, since tokens are cheap to create.
Revoking a token early
If a token leaks, you do not have to wait for it to expire. Call DELETE /installation/token with the installation token itself:
curl -L -X DELETE \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $INSTALLATION_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/installation/tokenGitHub returns 204 No Content, and the token stops working. If the private key itself may have leaked, revoking one token is not enough. Generate a new private key in the app settings and delete the old one. A later chapter covers key rotation.
Installation token or user token?
An installation token acts as the app, with no human involved. This suits automation such as bots, scheduled jobs, and webhook handlers. When the action must be attributed to a specific person and limited by what that person can see, you use a user access token instead. The next chapter covers that case.
Exercise
Your webhook handler needs to comment on issues in one repository, but the installation covers 40 repositories and grants contents: write and issues: write. How would you request the installation token, and what happens if you ask for pull_requests: write when the app lacks that permission?
Show answer
Send a POST to /app/installations/INSTALLATIONID/accesstokens, authenticated with the app JWT, and include a body such as {"repositories":["REPO"],"permissions":{"issues":"write"}}. The token then covers only that repository and only the issues permission. Requesting a permission the app does not have makes GitHub reject the request, typically with 422, because tokens can only narrow the installation's access, never widen it.
Exercise
A job runs every few seconds and gets 401 Unauthorized on API calls roughly once an hour, though the JWT code is correct. What is the most likely cause, and how do you fix it?
Show answer
The cached installation token expires after one hour. Store expires_at with the token and create a new token when less than a few minutes remain, or use Octokit's App class, which renews tokens automatically.