Sub topic 10
Authenticating as the app with a JWT
This chapter covers the first step of GitHub App authentication: proving to GitHub that a request comes from the app itself. It assumes you can make HTTP requests with curl, set environment variables in a terminal, and read basic JavaScript. You should also know what a GitHub App is and what an installation is, from the earlier chapters. The next chapter covers the second step, exchanging this credential for an installation access token.
Why an app needs its own credential
A personal access token belongs to a person. A GitHub App is not a person, so it needs a different way to prove who it is. When you register an app, GitHub gives it an App ID and lets you generate a private key. The private key is a file in PEM format that only you hold. GitHub keeps the matching public key.
The app does not send the private key over the network. It uses the key to sign a small document called a JSON Web Token (JWT). GitHub checks the signature with the public key. A valid signature shows that the sender holds the private key, so the sender is the app.
This is why the JWT is the credential for acting as the app, not as any account. With it you can call the endpoints that manage the app itself. These include listing its installations and creating installation access tokens. You cannot use it to read repository contents. For that, you need an installation access token, which the next chapter covers.
What a JWT contains
A JWT is three Base64URL-encoded parts joined by dots: a header, a payload, and a signature.
- The header names the signing algorithm. GitHub requires
RS256, which means RSA signatures with SHA-256. - The payload holds claims, which are fields that describe the token.
- The signature is computed over the header and payload with your private key.
GitHub requires these claims in the payload:
| Claim | Meaning | Value for a GitHub App |
|---|---|---|
| `iss` | Issuer, the party that created the token | The app's ID (GitHub also accepts the client ID) |
| `iat` | Issued at, a Unix timestamp in seconds | The current time, minus 60 seconds |
| `exp` | Expiration, a Unix timestamp in seconds | At most 10 minutes after the current time |
The JWT is not encrypted. Anyone who sees it can decode the payload. What protects it is the signature, which no one can forge without the private key, and the short lifetime.
Signing a JWT in JavaScript
The following script reads the private key from a file, builds the claims, and signs the token. It uses the jsonwebtoken package. Install it with npm install jsonwebtoken. Because the script uses import syntax, run it as an ES module, for example by naming the file jwt.mjs.
import fs from "node:fs";
import jwt from "jsonwebtoken";
const privateKey = fs.readFileSync(process.env.GITHUB_APP_PRIVATE_KEY_PATH, "utf8");
const now = Math.floor(Date.now() / 1000);
const appJwt = jwt.sign(
{
iat: now - 60,
exp: now + 600,
iss: process.env.GITHUB_APP_ID,
},
privateKey,
{ algorithm: "RS256" }
);
console.log(appJwt);Before you run it, set two environment variables. GITHUB_APP_ID is the app's ID from its settings page. GITHUB_APP_PRIVATE_KEY_PATH is the path to the .pem file you downloaded when you generated the key.
Three details in this script matter:
iatis set 60 seconds in the past. Your server's clock and GitHub's clock are rarely perfectly aligned. If your clock runs ahead, GitHub would see a token issued in the future and reject it. Backdating gives you a margin.expis set 600 seconds ahead, which is the 10-minute maximum. If you ask for more, GitHub rejects the token.Math.floor(Date.now() / 1000)converts milliseconds to seconds. JWT timestamps are in seconds, and passing milliseconds is a common mistake that produces an expiration far in the future.
Because the token lives only 10 minutes, you do not store it. Generate a new one whenever you need to call an app-level endpoint.
Using the JWT in a request
You send the JWT as a bearer token, the same way you send a personal access token. The only difference is the value.
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/appThe GET /app endpoint returns details about the authenticated app, such as its name, owner, and permissions. It is the standard way to check that your JWT works. If it returns your app's data, the ID, key, and claims are all correct.
Other endpoints that accept a JWT include GET /app/installations, which lists every account where the app is installed, and POST /app/installations/{installation_id}/access_tokens, which creates an installation access token. The second one is the bridge to the next chapter.
Using Octokit instead
You can sign JWTs by hand, and it helps to understand how. In real code, though, the octokit library can do the signing for you. The App class takes the app ID and private key, and it creates JWTs when it needs them.
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 { data } = await app.octokit.request("GET /app");
console.log(data.name);Here app.octokit is a client authenticated as the app. Each request uses a fresh JWT. You do not manage iat and exp yourself. The hand-written version is still useful when you work in another language or debug an authentication failure, because you can see each claim.
Common errors and how to read them
When a JWT is wrong, GitHub returns 401 Unauthorized. The response body usually says why.
| Symptom | Likely cause | Fix |
|---|---|---|
| `'Expiration time' claim ('exp') must be a numeric value representing the future time at which the assertion expires` | `exp` was in milliseconds, missing, or in the past | Use seconds. Set `exp` to `now + 600` |
| `'Expiration time' claim ('exp') is too far in the future` | `exp` is more than 10 minutes after the time GitHub sees | Lower the lifetime. Check for clock skew in your system |
| `'Issued at' claim ('iat') must be an Integer representing the time that the assertion was issued` | `iat` is in the future, because of clock drift or a unit mistake | Backdate `iat` by 60 seconds and use seconds |
| `A JSON web token could not be decoded` | Wrong algorithm, wrong key, or a malformed token | Use `RS256` and the key that belongs to this app |
| `Bad credentials` | Token is expired, or the key was deleted from the app settings | Generate a new JWT. Check that the key still exists |
Two points are worth remembering when you debug:
- A key that has been deleted from the app's settings stops working at once. An app can have more than one active key, which lets you rotate keys without downtime. The last chapter on credential hygiene returns to this.
- If the same code works on your laptop but fails on a server, compare the system clocks first. A server whose clock is a few minutes off causes most of the
iatandexperrors.
Handling the private key
The PEM file is the most sensitive thing in your app. Anyone who holds it can sign JWTs as your app and then request installation tokens for every account that installed it.
- Do not commit the file to a repository, and do not put it in a container image.
- Load it from a secret manager or a protected file path. Read the path from an environment variable, as the examples do.
- If you must put the key in an environment variable, such as in a CI system, newlines can be mangled. A key whose line breaks are lost fails to parse. Store it so the
-----BEGINand-----ENDlines and the lines between them are preserved. - If you suspect exposure, generate a new key in the app settings, deploy it, then delete the old one.
Summary of the flow
The JWT step is small but everything else depends on it. You hold a private key. You sign three claims with it. GitHub verifies the signature and the time window. You then call app-level endpoints, most importantly the one that creates an installation access token. Keep the JWT short-lived and never store it. Protect the key.
Exercise
Your script signs a JWT with exp set to Date.now() + 600 and receives a 401 error. What is wrong, and what is the corrected code for the claims? Also explain why iat is set to now - 60.
Show answer
Date.now() returns milliseconds, but JWT claims use seconds. Adding 600 produces a timestamp far in the future, which GitHub rejects. Compute const now = Math.floor(Date.now() / 1000); and use iat: now - 60, exp: now + 600. The iat is backdated by 60 seconds to allow for clock drift. If your clock is ahead of GitHub's, an iat equal to your current time would look like it was issued in the future and be rejected.
Exercise
A teammate says, "The JWT is encrypted, so it is safe to log it." Is that correct? What can a JWT be used for, and what cannot it be used for?
Show answer
It is not correct. A JWT is signed, not encrypted, so anyone can decode and read its claims. It should not be logged. While valid, it lets the holder call app-level endpoints such as GET /app, GET /app/installations, and the endpoint that creates installation access tokens, so a logged JWT is usable for up to 10 minutes. It cannot read or write repository contents directly. That requires an installation access token.