Sub topic 3
Fine-grained personal access tokens
This chapter assumes you know how bearer tokens authenticate API requests and why a classic token with broad scopes is risky. It also assumes you can use a terminal and environment variables. Here you will build the working model of a fine-grained personal access token (PAT), create one, call the API with it, and diagnose the errors you are most likely to hit.
What a fine-grained PAT is
A fine-grained personal access token is a credential you create for your own account. It acts as you, but it can do less than you can. A classic token is limited only by OAuth scopes such as repo, and one scope covers every repository you can reach. A fine-grained token is limited along three separate axes:
- Resource owner: exactly one user account or one organization.
- Repository access: public repositories only, all repositories of that owner, or a chosen list.
- Permissions: a named access level for each capability, such as reading contents or writing issues.
The token can never exceed what your own account can do. If you lose access to a repository, the token loses it too. Fine-grained tokens start with the prefix github_pat_, which makes them easy to find with secret scanners.
| Property | Classic PAT | Fine-grained PAT |
|---|---|---|
| Scope of access | All repositories you can reach | One resource owner, selected repositories |
| Permission model | Coarse OAuth scopes | Per-capability access levels |
| Expiration | Optional, often none | Set at creation, with owner-enforced limits |
| Organization control | Limited | Approval and lifetime policies |
| Prefix | `ghp_` | `github_pat_` |
The request model
Every request carries the token in the Authorization header. GitHub then makes a series of checks, and the order explains most error messages.
This order shows that a 401 means GitHub does not accept the token itself. A 403 or 404 means the token is accepted but its grants do not cover the request.
Choosing a resource owner and repositories
When you create the token, you pick one resource owner. This is the most common source of confusion. A token whose owner is your personal account cannot touch repositories owned by an organization, even if you are an admin there. To work in two organizations, create two tokens.
For repository access, you have three choices:
- Public repositories (read-only). The token can read public data and nothing else. Use it to avoid unauthenticated rate limits.
- All repositories. The token covers every repository the owner has now and any created later. This is convenient, but the grant grows without you noticing.
- Only select repositories. You choose a list. New repositories are not included. Prefer this option for scripts and CI jobs.
Some rules apply to the owner choice:
- If the owner is an organization, the organization must allow fine-grained tokens. Administrators can restrict them.
- If the organization requires approval, a token that requests private resources stays pending. It works only for public resources until an owner approves it.
- Resources owned by an enterprise account, rather than a user or organization, are not covered by this token type.
Setting permissions
Permissions fall into three groups. Repository permissions apply to the repositories you selected, for example Contents, Issues, Pull requests, Actions, and Metadata. Organization permissions apply to the organization, for example Members. Account permissions apply to your user account, for example Email addresses. You see only the groups that apply to your chosen owner.
Each permission has an access level. Most offer No access, Read-only, and Read and write. A few, such as Administration, behave differently, so read the description beside each one.
Two details matter in practice:
- Metadata read access is mandatory. GitHub adds it automatically whenever you select any repository permission. It exposes basic repository information, which is why a token with only a "Contents" grant can still fetch
GET /repos/OWNER/REPO. - Permissions are per endpoint. Creating a pull request needs Pull requests write. Creating a comment on that pull request might need Issues write instead, because GitHub treats pull request conversation comments as issue comments. The REST documentation lists the required permission under each endpoint. The same information also comes back in the
x-accepted-github-permissionsresponse header.
Start with the smallest set you think you need. Run the job, read the 403 responses, and add one permission at a time.
Creating a token
You create the token in the web interface. This is not available through the REST API.
- Open Settings, then Developer settings, then Personal access tokens, then Fine-grained tokens.
- Choose Generate new token.
- Enter a name that says what the token is for, for example
release-notes-bot. A good name makes later cleanup easier. - Choose a resource owner and an expiration.
- Choose repository access and select repositories.
- Add permissions.
- Generate the token and copy it. GitHub shows the value once.
Store the value in a secrets manager or an environment variable, not in source code. Chapter 14 covers storage in detail.
Calling the API
Export the token and make a request. The -i flag prints the response headers, which carry useful diagnostics.
export GITHUB_TOKEN="github_pat_REPLACE_ME"
curl -L -i \
-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/REPOLook for these response headers:
github-authentication-token-expirationshows when the token expires. Use it to warn yourself before a job starts failing.x-accepted-github-permissionslists the permissions the endpoint accepts.x-ratelimit-remainingshows how many requests you have left in the current window.
A small script can turn status codes into messages you can act on. This one needs Node.js 18 or later, which includes fetch, and it runs as an ES module (save it as check.mjs).
const token = process.env.GITHUB_TOKEN;
const repo = process.env.REPO; // for example "octocat/Hello-World"
if (!token || !repo) {
console.error("Set GITHUB_TOKEN and REPO first.");
process.exit(1);
}
const res = await fetch(`https://api.github.com/repos/${repo}/issues?per_page=1`, {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${token}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
console.log("Token expires:", res.headers.get("github-authentication-token-expiration"));
console.log("Endpoint accepts:", res.headers.get("x-accepted-github-permissions"));
if (res.status === 401) {
console.error("401: the token is invalid, expired, or revoked.");
} else if (res.status === 403) {
console.error("403: the token lacks a permission, or you hit a rate limit.");
} else if (res.status === 404) {
console.error("404: the repository does not exist, or the token cannot see it.");
} else if (res.ok) {
const issues = await res.json();
console.log(`OK. Received ${issues.length} issue(s).`);
} else {
console.error(`Unexpected status ${res.status}`);
}Expiration, approval and policy
A fine-grained token must have an expiration date, so you cannot create one that is forever valid by default. You can pick a preset such as 7, 30, 60, or 90 days, or a custom date. Organizations and enterprises can set a maximum lifetime, and a longer request is refused. Some owners allow no expiration; if you choose it, expect to be asked to justify it in review.
Organization owners control fine-grained tokens through policy. They can:
- Require approval before a token can access organization private resources.
- Restrict or block fine-grained tokens entirely.
- Review active tokens and revoke any of them.
Treat expiration as a feature. A token that dies in 30 days limits how long a leak stays useful.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 Bad credentials | Token expired, revoked, or copied with extra characters | Regenerate and check the header value |
| 403 "Resource not accessible by personal access token" | Missing permission, or owner mismatch | Check `x-accepted-github-permissions` and the resource owner |
| 404 on a private repository | Repository not selected, or approval pending | Add the repository, or ask an owner to approve |
| Works for public data only | Organization approval still pending | Contact an organization owner |
| Works in `curl`, fails in `git push` | Git uses the token as a password and needs Contents write | Add Contents write for that repository |
| Endpoint not supported | Some endpoints do not accept fine-grained tokens | Check the endpoint documentation, or use a GitHub App |
Some REST and GraphQL features do not yet work with fine-grained tokens, and GitHub's documentation lists them. If you need one of those features, the answer may be a different credential type, which later chapters compare.
Limits to keep in mind
- A token belongs to a person. If that person leaves the organization, the token stops working, and so does any automation that depends on it. This is a main reason to move long-running automation to a GitHub App.
- One token has one resource owner, so cross-organization automation needs several tokens.
- Rate limits attach to the user the token acts as, so many scripts sharing one person's tokens share one budget.
Exercise
A script uses a fine-grained token owned by your personal account. It calls GET /repos/my-org/api-service and receives 404, although you are an admin of my-org and the repository exists. Name two possible causes and the fix for each.
Show answer
First, the resource owner is wrong. A token owned by a personal account cannot reach organization repositories, so create a token whose resource owner is my-org. Second, the token is owned by my-org but the repository is not selected, or the organization requires approval and an owner has not yet approved the token. Add api-service to the token's repository list, or ask an owner to approve the token.
Exercise
Your job gets 403 "Resource not accessible by personal access token" when it creates an issue comment. Which response header tells you the accepted permissions, and what is a sound way to find the minimum permission to add?
Show answer
The x-accepted-github-permissions response header lists the permissions the endpoint accepts. Start with the smallest grant, read that header on the failing response, and add only the listed permission (for issue comments, Issues write) at the lowest level that works.