Sub topic 1
How API Authentication with Tokens Works
Prerequisites
You should know the basics of GitHub repositories, organizations, HTTP requests, REST APIs, terminals, environment variables, and bearer tokens. A bearer token is a secret string that proves a request is authorized.
Token Authentication
The GitHub REST API receives an HTTP request. The request includes an Authorization header containing a token:
export GITHUB_TOKEN='replace-with-your-token'
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/REPOGitHub checks the token, its permissions, and the target resource. If all checks pass, the API returns the requested data. A missing, invalid, expired, or insufficiently permitted token produces an error.
Classic Tokens and Broad Scopes
A classic personal access token is tied to a user account and uses broad scopes. A scope is a named group of permissions, such as access to repositories or organization data. For example, a token with the repo scope can provide wide access to private repositories available to that user.
This model is simple, but a stolen token may expose much more than one script needs. Broad scopes also make audits and incident response harder.
Fine-Grained Personal Access Tokens
A fine-grained personal access token limits access along several dimensions:
- A resource owner, such as your account or an organization.
- Selected repositories owned by that resource owner.
- Specific repository permissions, such as read-only issues or read-and-write contents.
- An expiration date.
The API request looks the same, but GitHub evaluates these narrower rules. A script that only reads one repository can receive read-only access to that repository instead of broad access to every repository.
Choosing the Resource Owner and Repositories
Choose the resource owner that owns the target repository. Then select only the repositories the script must use. Finally, choose the lowest permission level that supports the operation.
For example, a reporting script that reads issues should use one owner, selected repositories, and read-only Issues permission. It should not receive write access to repository contents.
Exercise
A deployment script needs to read one repository's contents and create issues there. What access should its fine-grained token have?
Show answer
Select the repository's owner and that repository only. Grant read-only Contents permission and read-and-write Issues permission, with an expiration date.