Sub topic 1
How API authentication with tokens works
Every GitHub credential covered in this tutorial is a bearer token sent in an HTTP header. This chapter gives you the working model for that exchange. It covers what GitHub checks on each request, how to send a token, how to read the responses, and which errors you will see most often. Later chapters build on it when they compare token types.
Prerequisites
This chapter assumes you can:
- Work with GitHub repositories and organizations at the level of creating a repository and inviting a collaborator.
- Read and send HTTP requests, including headers, status codes, and JSON bodies.
- Use a terminal and set environment variables.
- Explain in one sentence what a bearer token is: a secret string where possession alone proves the right to use it.
You also need curl. The Node.js example needs Node 18 or later.
Authentication and authorization are separate checks
When a request reaches api.github.com, GitHub answers two questions in order.
- Authentication: who is making this request? GitHub looks up the token you sent and finds the identity behind it. That identity might be a user, a GitHub App, or an app installation.
- Authorization: is that identity allowed to do this particular thing to this particular resource? The answer depends on the token's limits and on what the underlying identity can do.
A token never grants more than its owner could do. A token also never grants more than the token itself allows. The effective access is the overlap of the two. Keep this overlap in mind, because the rest of the tutorial is about shrinking the token's side of it.
| Layer | Question | Example of what narrows it |
|---|---|---|
| Identity | Who are you? | The user or app that owns the token |
| Owner's access | What can that identity reach? | Repository membership, organization role |
| Token limits | What did this token's creator allow? | Scopes, repository selection, permissions |
| Result | What can this request do? | The intersection of the three rows above |
What a bearer token is
A bearer token is a string that GitHub issued and that you present with every request. GitHub does not ask you to prove you are the original holder. Anyone who has the string can act with it until it expires or is revoked. That is why storage and scope matter so much.
GitHub gives each credential type a recognizable prefix. The prefix helps you identify a token in a log or a secret scanner, and it lets GitHub's secret scanning detect leaks.
| Prefix | Credential type |
|---|---|
| `ghp_` | Classic personal access token |
| `github_pat_` | Fine-grained personal access token |
| `gho_` | OAuth app user access token |
| `ghu_` | GitHub App user access token |
| `ghs_` | GitHub App installation access token |
| `ghr_` | Refresh token |
The prefix tells you the type. It does not tell you the token's limits. For those you need to inspect the token's settings or the response headers, as shown later.
Sending a token
Send the token in the Authorization header with the Bearer scheme. Add the media type and API version headers too.
curl -L \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/OWNER/REPOEach header has a job:
Authorization: Bearer ...carries the credential. GitHub also accepts the oldertokenscheme, butBearerworks for every token type here, and it is required for the JWT you will use in a later chapter.Accept: application/vnd.github+jsonrequests the standard JSON response format.X-GitHub-Api-Versionpins the REST API version, so a future change in default behavior does not alter your responses.-Lmakes curl follow redirects. GitHub redirects renamed or transferred repositories, and without-Lyou would receive an empty redirect response instead of data.
This request looks the same for a fine-grained personal access token and for an installation access token. Only the string in $GITHUB_TOKEN changes. Because the wire format is identical, the choice of credential is a question of limits and lifecycle. It is not a question of how your code makes calls.
Set the variable without writing the secret into your shell history on a shared machine. Reading it from a prompt is one way:
read -rs GITHUB_TOKEN
export GITHUB_TOKENThe -s flag stops the terminal from echoing what you type.
The same call in Node.js
Node 18 and later include fetch, so you can make the request with no dependencies. This script reads the token from the environment and prints the status code, rate limit headers, and repository name.
const token = process.env.GITHUB_TOKEN;
if (!token) {
throw new Error("Set GITHUB_TOKEN first");
}
const response = await fetch("https://api.github.com/repos/octocat/Hello-World", {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${token}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
console.log("status:", response.status);
console.log("rate limit remaining:", response.headers.get("x-ratelimit-remaining"));
console.log("rate limit resets at:", response.headers.get("x-ratelimit-reset"));
if (response.ok) {
const repo = await response.json();
console.log("repository:", repo.full_name);
} else {
console.log("error body:", await response.text());
}Save it as check.mjs and run node check.mjs. The .mjs extension lets Node accept top-level await.
The request lifecycle
Reading responses and diagnosing errors
Most authentication problems fall into a few status codes. Knowing which check failed saves a lot of guessing.
| Status | Typical message | Meaning | Usual fix |
|---|---|---|---|
| 200 | (JSON body) | Authenticated and authorized | None |
| 401 | `Bad credentials` | GitHub could not match the token to an identity | Check for a typo, an expired token, a revoked token, or an empty variable |
| 403 | `Resource not accessible by integration` | The identity is valid but the token lacks the permission | Add the permission, or use a token for a different identity |
| 403 | `API rate limit exceeded` | You used your request allowance | Wait until the reset time, then reduce calls |
| 404 | `Not Found` | The resource does not exist, or the token cannot see it | Check the repository name, then check the token's repository access |
Two points here surprise people.
A missing permission can look like a 404. For private repositories, GitHub often returns 404 when your token cannot see the resource. This avoids confirming that a private repository exists. If a repository you know exists returns 404, suspect the token's repository selection before you suspect a typo.
An empty environment variable gives a 401. If $GITHUB_TOKEN is unset, the header becomes Authorization: Bearer with no value, and GitHub rejects it. Run echo "${GITHUB_TOKEN:+set}" to confirm the variable has a value without printing the secret.
Headers that explain access
GitHub includes headers that help you see what a token can do.
x-oauth-scopeslists the scopes of a classic token.x-accepted-oauth-scopeslists the scopes the endpoint accepts. Fine-grained tokens and app tokens do not use scopes, so these headers do not describe them.x-accepted-github-permissionsnames the fine-grained permissions an endpoint needs. When a fine-grained or app token gets a 403, compare this header with the permissions you granted.x-ratelimit-limit,x-ratelimit-remaining, andx-ratelimit-resetdescribe your rate limit. The reset value is a Unix timestamp in seconds.
To see them, ask curl to print response headers:
curl -sS -D - -o /dev/null \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/OWNER/REPO-D - writes headers to standard output, and -o /dev/null discards the body.
Rate limits depend on the credential
Rate limits attach to the identity behind the token. An unauthenticated request is limited per IP address, and the allowance is small (60 requests per hour for the REST API). An authenticated user is allowed 5,000 requests per hour. App installation tokens have their own limits, and these can be higher for installations on larger organizations. The exact numbers change, so read x-ratelimit-limit from a real response instead of hard-coding a value.
One consequence matters in practice. Several tokens owned by the same user share that user's allowance. Splitting work across more personal tokens does not raise the limit. An app has its own allowance separate from any user, which is one reason automation tends to move to apps.
Why this model shapes the rest of the tutorial
The request format never changes, but three properties of the token do:
- Whose identity it carries. A personal token acts as a person. An installation token acts as an app on one account.
- How narrow its limits are. A classic token's scopes cover whole categories of access. Fine-grained tokens and app tokens limit access by repository and by individual permission.
- How long it lives. Some tokens last until you delete them. Installation tokens expire after one hour.
Because a bearer token works for anyone who holds it, narrow limits and short lifetimes are your main protection when a token leaks. The following chapters cover how to get both.
Summary
- GitHub authenticates a request by resolving the bearer token to an identity, then authorizes it against the token's limits and the identity's own access.
- All token types use the same
Authorization: Bearerheader, so the differences between them are about limits and lifetime. - A 401 means the token was not recognized. A 403 usually means a missing permission or an exhausted rate limit. A 404 on a private resource can mean the token cannot see it.
- Response headers such as
x-accepted-github-permissionsandx-ratelimit-remainingshow you why a call succeeded or failed.
Exercise
You call GET /repos/acme/payments with a token. You know the private repository acme/payments exists, and you can open it in your browser. The API returns 404 Not Found, while GET /repos/octocat/Hello-World with the same token returns 200. What are the two most likely causes, and how would you tell them apart?
Show answer
The token's own limits probably exclude the repository, or the token's identity cannot access it. For a fine-grained token, the repository may not be in its selected repositories, or the token may lack the repository permission the endpoint needs. For an app installation token, the app may not be installed on that repository. The public repository works because anyone can read it. To tell the causes apart, call an endpoint that works with any valid token, such as GET /user for a personal token, to confirm the token is valid. Then check the token's repository selection in its settings. Also check the x-accepted-github-permissions header to see which permission the endpoint requires. A 401 would have meant a bad token. Here the token is valid, so the problem is its reach.
Exercise
A script sets Authorization: Bearer $GITHUB_TOKEN but returns 401 Bad credentials, even though the token worked yesterday in the same terminal. Name two checks you would make, without printing the token.
Show answer
First, confirm the variable still has a value, for example with echo "${GITHUB_TOKEN:+set}". A new shell session or a different working environment often leaves it empty. Second, check whether the token expired or was revoked in the GitHub settings. Fine-grained tokens have expiration dates, and installation tokens last only one hour. If the token is gone or past its expiry, GitHub cannot match it to an identity and returns 401.