Sub topic 12
User access tokens for acting on behalf of a user
This chapter assumes you have read the earlier chapters on GitHub Apps, installations, app permissions, and installation access tokens. It also assumes you can read basic Node.js and HTTP. A GitHub App can act as itself through an installation access token. Sometimes the app must act as a specific person instead. A user access token covers that case.
When an app needs a user token
An installation access token represents the app. Commits, comments, and issues it creates are attributed to the app's bot account, such as my-app[bot]. That is right for automation like CI bots and release tooling.
Some work needs to be attributed to a person, or needs to see only what a person can see:
- A web app that shows "your repositories" after the user signs in with GitHub.
- A tool that opens a pull request that should appear under the user's name.
- A dashboard that must not reveal private repositories the viewer cannot access.
For these cases, the app uses a user access token. GitHub's documentation also calls this a user-to-server token. The user authorizes the app through an OAuth-style flow, and GitHub issues a token tied to both that user and that app.
What limits a user access token
A user access token never grants more than the user and the app each have. Its effective access is the intersection of three things:
- The permissions the GitHub App requested in its settings.
- The repositories where the app is installed.
- What the user can access themselves.
If the app has Contents: write, but the user only has read access to a repository, the token can only read it. If the user has admin access to a repository where the app is not installed, the token still cannot reach it.
GitHub Apps do not use OAuth scopes like repo or read:org. Do not pass a scope parameter and expect it to matter. Permissions come from the app's configuration, which is the main safety advantage over an OAuth app.
| Property | Installation access token | User access token |
|---|---|---|
| Acts as | The app (bot) | The user, through the app |
| Obtained with | Signed JWT | User authorization (OAuth web or device flow) |
| Needs a user present | No | Yes, at least once |
| Token prefix | `ghs_` | `ghu_` |
| Lifetime | 1 hour | 8 hours by default (expiring) |
| Refreshable | No, mint a new one | Yes, with a refresh token |
| Bounded by | App permissions and installation repositories | App permissions, installation repositories, and the user's own access |
The web application flow
The web flow is the standard way to get a user token. The app needs its client ID and a client secret, both shown on the app's settings page. You must also set a callback URL there.
The flow has these steps:
- The app redirects the user's browser to GitHub's authorize URL, including a random
statevalue. - The user approves the request.
- GitHub redirects back to the callback URL with a temporary
codeand the samestate. - The app checks
state, then exchanges thecodefor tokens by sending it with its client secret to GitHub.
The state value protects against cross-site request forgery. Without it, an attacker could trick a user's browser into completing a flow that the attacker started, which attaches the attacker's authorization to the victim's session. Generate it randomly and compare it on return.
A minimal implementation
This Express server implements both ends of the flow. It keeps state values in memory and the token in a variable, which is only suitable for a demo. Install express first with npm install express, and run it on Node.js 18 or later. Save it as an ES module, such as server.mjs.
import crypto from "node:crypto";
import express from "express";
const { GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, CALLBACK_URL } = process.env;
const pendingStates = new Set();
const app = express();
app.get("/login", (req, res) => {
const state = crypto.randomBytes(16).toString("hex");
pendingStates.add(state);
const url = new URL("https://github.com/login/oauth/authorize");
url.searchParams.set("client_id", GITHUB_CLIENT_ID);
url.searchParams.set("redirect_uri", CALLBACK_URL);
url.searchParams.set("state", state);
res.redirect(url.toString());
});
app.get("/callback", async (req, res) => {
const { code, state } = req.query;
if (!state || !pendingStates.delete(state)) {
return res.status(400).send("Invalid state");
}
const tokenResponse = await fetch("https://github.com/login/oauth/access_token", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({
client_id: GITHUB_CLIENT_ID,
client_secret: GITHUB_CLIENT_SECRET,
code,
redirect_uri: CALLBACK_URL,
}),
});
const tokens = await tokenResponse.json();
if (tokens.error) {
return res.status(400).send(tokens.error_description);
}
const userResponse = await fetch("https://api.github.com/user", {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${tokens.access_token}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
const user = await userResponse.json();
res.send(`Signed in as ${user.login}. Token expires in ${tokens.expires_in} seconds.`);
});
app.listen(3000, () => console.log("Listening on http://localhost:3000"));Set CALLBACK_URL to http://localhost:3000/callback and register that same value as the app's callback URL. Then open /login in a browser.
GitHub returns HTTP 200 even for failed exchanges, with an error field in the JSON body. Always check for error, as the code above does. A common failure is bad_verification_code. It happens when a code is reused or has expired, because codes are single-use and valid for only 10 minutes.
Expiring tokens and refresh
New GitHub Apps issue expiring user tokens by default. The response includes these fields:
access_token: starts withghu_and lasts 8 hours (expires_inis 28800).refresh_token: starts withghr_and lasts about six months.refresh_token_expires_in: the refresh token's lifetime in seconds.
When the access token expires, the API returns 401 Bad credentials. The app then exchanges the refresh token for a new pair:
async function refreshUserToken(refreshToken) {
const response = await fetch("https://github.com/login/oauth/access_token", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
grant_type: "refresh_token",
refresh_token: refreshToken,
}),
});
const tokens = await response.json();
if (tokens.error) {
throw new Error(`Refresh failed: ${tokens.error}`);
}
return tokens;
}Refresh tokens are single-use. Each refresh returns a new access token and a new refresh token, and the old refresh token stops working. You must persist the new refresh token before you discard the old one. If two requests refresh at the same moment, one of them will fail, and the user may have to sign in again. Serialize refreshes per user, for example with a lock around the refresh call.
Device flow for terminals and headless tools
A command-line tool cannot receive a browser redirect. For that case, enable Device Flow in the app's settings. The tool requests a device code with POST https://github.com/login/device/code and its client_id. GitHub returns a short user_code and a verification URL (https://github.com/login/device). The tool shows the code to the user, who enters it in any browser. Meanwhile the tool polls POST https://github.com/login/oauth/access_token with grant_type=urn:ietf:params:oauth:grant-type:device_code until the user approves.
Device flow needs no client secret and no callback URL. The result is the same kind of user token as in the web flow.
Using the token
Send the user token like any other bearer token:
curl -L \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $USER_ACCESS_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/user/installationsGET /user/installations lists the installations of your app that this user can access. To list repositories within one, call GET /user/installations/{installation_id}/repositories. These two endpoints work only with user access tokens, and they show what the user and app share.
Not every endpoint accepts a user access token. Each endpoint's reference page lists the token types it supports. A request can return 403 or 404 because the app lacks the permission, because the app is not installed on that repository, or because the user cannot see the resource. The error alone does not say which.
Choosing between the two app tokens
Use an installation access token when the work is automated and should appear as the app. Use a user access token when the action must be attributed to a person, or when the data returned must match that person's visibility. Using an installation token to serve user-specific data is a common mistake. It can expose repositories the viewer should not see, since the token covers everything the installation can reach.
Keep in mind that user tokens carry more rate-limit constraints. Each user and app pair has its own limit, which is separate from the installation's limit. That is useful, because many users do not share one budget.
Revoking and cleaning up
Users can revoke an app's authorization under Settings, Applications, Authorized GitHub Apps. The app can also revoke on its own, using the client ID and secret as HTTP basic credentials:
DELETE /applications/{client_id}/tokenrevokes one access token.DELETE /applications/{client_id}/grantrevokes the user's whole authorization and all of its tokens.
Revoke when a user signs out or deletes their account, and when you suspect a token has leaked. If a user revokes access, your next call returns 401, and refresh will fail. Handle that by prompting the user to sign in again, not by retrying.
Exercise
Your GitHub App has Contents: write and is installed on repositories A and B. A user has write access to A and B, but also admin access to repository C, where the app is not installed. What can this user's access token do with repository contents? And what happens if your server refreshes the token and then crashes before saving the new refresh token?
Show answer
The token can write contents in A and B, since all three limits allow it. It cannot touch C, because the app is not installed there, even though the user has admin rights. After the crash, the old refresh token is invalid because refresh tokens are single use, and the new one was lost. The user must go through authorization again. To prevent this, persist the new tokens durably as part of the refresh and serialize refreshes per user.