← All articles
Best PracticesNov 29, 202616 min read

Secure GitHub Personal Access Tokens: A Step-by-Step Guide

Serdal Tarkan AltunSecurity Research EngineerLinkedIn

Summary

A GitHub personal access token (PAT) replaces your password for Git over HTTPS and the GitHub API, and it carries your access until it expires or is revoked. To secure PATs, create fine-grained tokens with one resource owner, selected repositories, minimal permissions and an expiry, then enforce organization policies, review active tokens and replace PATs with GitHub Apps.

Quick steps

  1. Create fine-grained tokens: one resource owner, Only select repositories, the fewest permissions and an expiration date.
  2. Run the read-only inventory script with a GitHub App token to export approved tokens, pending requests and SSO-authorized credentials.
  3. Keep Require administrator approval for fine-grained tokens and set a maximum lifetime for both token types.
  4. Restrict personal access tokens (classic) once their users have moved to fine-grained tokens or GitHub Apps.
  5. On GitHub Enterprise Cloud with SAML single sign-on (SSO), review the credentials members have authorized and revoke the unused ones.
  6. Turn on secret scanning and push protection, and revoke a leaked token at once.
  7. Replace automation tokens with GITHUB_TOKEN, GitHub App installation tokens and OpenID Connect (OIDC).
  8. Alert on token grants and token policy changes in the GitHub audit log.

Applies to: GitHub.com accounts, organizations and enterprises (as of November 2026). SAML single sign-on, the audit log API and audit log streaming need GitHub Enterprise Cloud. GitHub Enterprise Server versions differ and aren't covered. The scripts use GitHub CLI (gh) and bash.

What is a GitHub personal access token and why does it matter?

A GitHub personal access token is a credential you use instead of a password when you authenticate to GitHub from the command line or the API. GitHub's token documentation says a token has the same capabilities as its owner, further limited by its scopes or permissions. It can't grant more than the user holds, and it becomes inactive if the user loses access to the resource.

For Git over HTTPS, GitHub authenticates the token, not the username you type. Whoever holds a token can use it until it expires or someone revokes it. That makes PATs long-lived secrets: they end up in scripts, CI variables and config files, where they become a hardcoded credential risk.

An attacker who steals a token from a repository, a build log or a developer machine can use it as their own, which MITRE ATT&CK tracks as T1528, Steal Application Access Token. A classic token with broad scopes taken from an organization owner reaches every repository and setting that owner controls. Treat each PAT as a non-human identity with an owner, a purpose and an end date.

Fine-grained vs classic personal access tokens

GitHub supports two types and recommends fine-grained tokens whenever possible. Classic tokens remain for the few tasks fine-grained tokens can't do yet, and GitHub's token formats give each type its own prefix.

Fine-grained personal access token Personal access token (classic)
Resource owner One user or one organization Every account and organization you can access
Repository access All of the owner's repositories or only selected ones, plus read-only access to public repositories Every repository you can access
Permission model Fine-grained repository, organization and account permissions at read, write or admin Broad OAuth scopes such as repo or admin:org
Expiration Organizations cap the lifetime at 366 days by default No expiration requirement
Organization approval Owners can require approval for each token (on by default) Never subject to approval
Visible to organization owners Yes, in Personal access tokens > Active tokens Only as an SSO-authorized credential on GitHub Enterprise Cloud
SAML SSO Authorized while the token is created Must be authorized after creation
Prefix github_pat_ ghp_
Known gaps Outside collaborators, Packages, several organizations at once, the Checks API Supported

A user can create at most 50 fine-grained tokens. Classic tokens are still needed where outside collaborators access organization repositories or where a REST endpoint only supports them.

How do you create a fine-grained personal access token safely?

Create the token in your account settings, scope it to one owner and the repositories you need, give it the fewest permissions, and set an expiration date. If the organization requires approval, the token stays pending until an owner approves it.

  1. Verify your email address if you haven't yet.
  2. Select your profile picture, then Settings > Developer settings > Personal access tokens > Fine-grained tokens, and Generate new token.
  3. Enter a Token name that says what uses it, and add a Description.
  4. Under Expiration, pick the shortest period that fits the job. Infinite lifetimes are allowed, but an organization or enterprise lifetime policy can block them.
  5. Under Resource owner, select the organization. It doesn't appear if the organization has blocked fine-grained tokens. If the organization requires approval, enter a justification.
  6. Under Repository access, choose Only select repositories and pick them. Every token also keeps read-only access to all public repositories on GitHub.
  7. Under Permissions, apply least privilege: add only what the task needs. Each REST endpoint's reference page lists the permissions it requires.
  8. Select Generate token and store the value in a secret manager or an Actions secret, never in code.

Until an owner approves the request, the token can only read public resources. A request from an organization owner is approved automatically.

Share a least-privilege token template

Teams that need the same token can share a pre-filled creation link instead of a written checklist. GitHub accepts query parameters on https://github.com/settings/personal-access-tokens/new: name, description, target_name (the resource owner), expires_in (1 to 366 days, or none) and one parameter per permission. Without expires_in, the form proposes 30 days, or less under a lifetime policy.

https://github.com/settings/personal-access-tokens/new?name=release-notes-bot&description=Read+issues+for+release+notes&target_name=example-org&expires_in=30&issues=read

The link only fills in the form. It has no parameter for repository selection, so the user still picks the repositories, and the organization's approval and lifetime policies still apply.

Keep tokens off the command line

GitHub's own advice is to avoid a token where a safer method exists. Use GitHub CLI or Git Credential Manager for the command line, and GITHUB_TOKEN in Actions workflows. Don't pass a token as plain text on the command line or push it to any repository, even a private one.

When do you still need a personal access token (classic)?

Some tasks still need a classic token, such as an outside collaborator working in an organization repository. Create it under Developer settings > Personal access tokens > Tokens (classic), set an Expiration, and select only the scopes you need; a token without scopes can only read public information. In an organization that uses SAML SSO, authorize it with Configure SSO before it can reach the organization.

Before you start

Governing tokens across an organization changes how members and automation authenticate, so prepare the people, the plan and the tooling before you change anything. Test the policies in a test organization first, because restricting classic tokens breaks every script that still uses one to reach organization resources that aren't public.

  • Who: organization owners set organization token policies and see the organization's token pages. Enterprise owners set enterprise policies that organizations can't override.
  • Plans: SAML SSO, the audit log API and audit log streaming need GitHub Enterprise Cloud. The enterprise credential inventory in Step 1 also needs it.
  • Impact: a restricted classic token gets a 403 response. A lifetime policy blocks noncompliant tokens of organization members but doesn't revoke them, and users find out when their API calls are rejected.
  • Communication: tell members which policies change and when, and where to find the replacement options in Step 5.
  • Tooling: install GitHub CLI. The organization token endpoints work only for GitHub Apps, so register one for the inventory in Step 1.

Register a read-only GitHub App for the inventory

GitHub lets only GitHub Apps call the REST endpoints for personal access tokens that list and revoke an organization's fine-grained tokens. Personal access tokens and OAuth apps can't call them.

  1. Open the organization's Settings > Developer settings > GitHub Apps, then New GitHub App.
  2. Name it, enter a homepage URL, and clear Active under webhooks, because the inventory doesn't need events.
  3. Under Permissions, set these organization permissions to Read-only: Personal access tokens, Personal access token requests and, for the SSO report, Administration.
  4. Select Only on this account, create the app, generate a private key, and install the app on the organization.

The revocation script in Step 4 needs Personal access tokens at Read & write. Give that to a separate app, so the scheduled inventory stays read-only.

Step 1: Inventory personal access tokens in your organization

Start with a list of every token that can reach the organization, who owns it, what it can touch and when it was last used. Organization owners see approved fine-grained tokens under Settings > Personal access tokens > Active tokens and waiting requests under Pending requests, with filters for owner, repository and permission.

Classic tokens don't appear on those pages. On GitHub Enterprise Cloud with SAML SSO, they show up as credentials that members authorized for the organization (Step 3). Enterprise owners can also export a credential inventory from the enterprise Settings > Authentication security > Export CSV. It covers fine-grained and classic tokens, OAuth and GitHub App tokens and SSH keys, and never includes token values.

The script below collects the same organization data through the REST API. It is read-only and sends only GET requests. Run it with GitHub CLI, with a GitHub App installation access token in GH_TOKEN; GitHub CLI uses that variable before any stored credentials. The API returns metadata only, and the script drops the last characters of tokens that the SSO endpoint returns.

#!/usr/bin/env bash
#
# github-pat-inventory.sh
#
# Purpose:  Inventory personal access token (PAT) access to one GitHub
#           organization. Writes CSV reports and prints a summary:
#             fine-grained-pats.csv  approved fine-grained PATs
#             pending-requests.csv   fine-grained PAT requests awaiting approval
#             sso-credentials.csv    SAML SSO credential authorizations
#                                    (classic PATs, app tokens, SSH keys),
#                                    only with --with-sso
# Mode:     Read-only. Sends GET requests only and changes nothing. The API
#           returns token metadata, never token values, and the script leaves
#           out the last characters of tokens that the SSO endpoint returns.
# Auth:     Run gh with a GitHub App installation access token in GH_TOKEN.
#           GitHub lets only GitHub Apps call the PAT endpoints. Give the app
#           these organization permissions:
#             Personal access tokens: Read-only
#             Personal access token requests: Read-only
#             Administration: Read-only (needed only for --with-sso)
#           --with-sso also needs GitHub Enterprise Cloud with SAML SSO.
# Where:    A GitHub Actions job (pat-inventory.yml) or an admin workstation
#           with GitHub CLI (gh). gh evaluates the --jq filters itself.
# Usage:    github-pat-inventory.sh <org> <output-dir> [--with-sso] [--stale-days <n>]
# Example:  github-pat-inventory.sh example-org ./pat-inventory --with-sso --stale-days 90

set -euo pipefail

USAGE='usage: github-pat-inventory.sh <org> <output-dir> [--with-sso] [--stale-days <n>]'
ORG="${1:?$USAGE}"
OUT_DIR="${2:?$USAGE}"
shift 2

WITH_SSO=false
STALE_DAYS=90
while [ "$#" -gt 0 ]; do
  case "$1" in
    --with-sso) WITH_SSO=true; shift ;;
    --stale-days) STALE_DAYS="${2:?--stale-days needs a number of days}"; shift 2 ;;
    *) echo "Unknown option: $1" >&2; exit 2 ;;
  esac
done

if ! [[ "$ORG" =~ ^[A-Za-z0-9-]+$ ]]; then
  echo "The organization name may contain only letters, digits and hyphens." >&2
  exit 2
fi
if ! [[ "$STALE_DAYS" =~ ^[0-9]+$ ]]; then
  echo "--stale-days must be a whole number of days." >&2
  exit 2
fi
command -v gh >/dev/null 2>&1 || { echo "GitHub CLI (gh) is not installed." >&2; exit 1; }
mkdir -p "$OUT_DIR"

CUTOFF='((now - '"${STALE_DAYS}"' * 86400) | todate)'
UNUSED='"unused_'"${STALE_DAYS}"'d"'

# "repository:contents=read;organization:members=read" from the permissions object.
PERMS='[(.permissions // {}) | to_entries[] | .key as $scope | (.value // {}) | to_entries[] | "\($scope):\(.key)=\(.value)"] | join(";")'

FG_FINDINGS='[
  (if .token_expired then "expired" else empty end),
  (if .token_expires_at == null then "no_expiry" else empty end),
  (if .repository_selection == "all" then "all_repositories" else empty end),
  (if ([(.permissions // {})[] | (. // {})[]] | any(. == "write" or . == "admin")) then "write_or_admin" else empty end),
  (if ((.permissions.organization // {}) | length) > 0 then "organization_permissions" else empty end),
  (if (.token_last_used_at == null) or (.token_last_used_at < '"${CUTOFF}"') then '"${UNUSED}"' else empty end)
] | join(";")'

SSO_FINDINGS='[
  (if .credential_type == "personal access token" and .authorized_credential_expires_at == null then "no_expiry" else empty end),
  (if ((.scopes // []) | any(. == "repo" or . == "admin:org" or . == "workflow" or . == "delete_repo")) then "broad_scope" else empty end),
  (if (.credential_accessed_at == null) or (.credential_accessed_at < '"${CUTOFF}"') then '"${UNUSED}"' else empty end)
] | join(";")'

# 1. Approved fine-grained PATs that can access the organization
FG_CSV="$OUT_DIR/fine-grained-pats.csv"
echo 'findings,grant_id,token_id,token_name,owner,repository_selection,access_granted_at,token_expires_at,token_last_used_at,permissions' > "$FG_CSV"
gh api --method GET --paginate "/orgs/${ORG}/personal-access-tokens" -f per_page=100 \
  --jq ".[] | [(${FG_FINDINGS}), .id, .token_id, .token_name, .owner.login, .repository_selection, .access_granted_at, (.token_expires_at // \"\"), (.token_last_used_at // \"\"), (${PERMS})] | @csv" \
  >> "$FG_CSV"

# 2. Fine-grained PAT requests waiting for an owner's approval
REQ_CSV="$OUT_DIR/pending-requests.csv"
echo 'request_id,token_id,token_name,owner,created_at,repository_selection,token_expires_at,permissions,reason' > "$REQ_CSV"
gh api --method GET --paginate "/orgs/${ORG}/personal-access-token-requests" -f per_page=100 \
  --jq ".[] | [.id, .token_id, .token_name, .owner.login, .created_at, .repository_selection, (.token_expires_at // \"\"), (${PERMS}), ((.reason // \"\") | gsub(\"[\\r\\n]+\"; \" \"))] | @csv" \
  >> "$REQ_CSV"

# 3. Optional: credentials authorized for SAML SSO (the only org-level view of classic PATs)
SSO_CSV="$OUT_DIR/sso-credentials.csv"
if [ "$WITH_SSO" = true ]; then
  echo 'findings,login,credential_type,credential_id,credential_authorized_at,credential_accessed_at,authorized_credential_expires_at,scopes' > "$SSO_CSV"
  gh api --method GET --paginate "/orgs/${ORG}/credential-authorizations" -f per_page=100 \
    --jq ".[] | [(${SSO_FINDINGS}), .login, .credential_type, .credential_id, .credential_authorized_at, (.credential_accessed_at // \"\"), (.authorized_credential_expires_at // \"\"), ((.scopes // []) | join(\";\"))] | @csv" \
    >> "$SSO_CSV"
fi

# 4. Summary (findings is the first column, so each count reads only that field)
rows() { echo $(( $(wc -l < "$1") - 1 )); }
flag() { grep -c "^\"[^\"]*$2" "$1" || true; }

printf 'Organization                : %s\n' "$ORG"
printf 'Fine-grained PATs approved  : %s\n' "$(rows "$FG_CSV")"
printf '  no_expiry                 : %s\n' "$(flag "$FG_CSV" no_expiry)"
printf '  all_repositories          : %s\n' "$(flag "$FG_CSV" all_repositories)"
printf '  write_or_admin            : %s\n' "$(flag "$FG_CSV" write_or_admin)"
printf '  unused_%sd                : %s\n' "$STALE_DAYS" "$(flag "$FG_CSV" "unused_${STALE_DAYS}d")"
printf 'Pending requests            : %s\n' "$(rows "$REQ_CSV")"
if [ "$WITH_SSO" = true ]; then
  printf 'SSO-authorized credentials  : %s\n' "$(rows "$SSO_CSV")"
  printf '  broad_scope               : %s\n' "$(flag "$SSO_CSV" broad_scope)"
  printf '  no_expiry                 : %s\n' "$(flag "$SSO_CSV" no_expiry)"
fi
printf 'Reports                     : %s\n' "$OUT_DIR"

The simplest way to give the script an installation token is a scheduled workflow. GitHub's documented pattern uses the GitHub-owned actions/create-github-app-token action, and the token it creates is revoked when the job finishes. Save the file as .github/workflows/pat-inventory.yml and the script as scripts/github-pat-inventory.sh in a private repository that only administrators can change. On GitHub Enterprise Cloud with SAML SSO, add --with-sso to the run line.

# .github/workflows/pat-inventory.yml
# Read-only weekly inventory of personal access token access to this organization.
# Needs: a GitHub App installed on the organization with the read-only permissions
# listed in scripts/github-pat-inventory.sh, its client ID in the configuration
# variable PAT_INVENTORY_APP_CLIENT_ID and its private key in the secret
# PAT_INVENTORY_APP_PRIVATE_KEY. Keep this workflow in a private repository
# that only administrators can write to.
name: PAT inventory

on:
  workflow_dispatch:
  schedule:
    - cron: '0 6 * * 1'

permissions:
  contents: read

jobs:
  inventory:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - name: Create a GitHub App installation token
        id: app-token
        uses: actions/create-github-app-token@v3
        with:
          client-id: ${{ vars.PAT_INVENTORY_APP_CLIENT_ID }}
          private-key: ${{ secrets.PAT_INVENTORY_APP_PRIVATE_KEY }}
          owner: ${{ github.repository_owner }}

      - name: Run the read-only inventory
        env:
          GH_TOKEN: ${{ steps.app-token.outputs.token }}
          ORG: ${{ github.repository_owner }}
        run: bash scripts/github-pat-inventory.sh "$ORG" pat-inventory --stale-days 90

      - name: Keep the reports for 30 days
        uses: actions/upload-artifact@v4
        with:
          name: pat-inventory
          path: pat-inventory
          retention-days: 30

Run it by hand from an admin workstation the same way, after you set GH_TOKEN to an installation token:

bash scripts/github-pat-inventory.sh example-org ./pat-inventory --with-sso --stale-days 90

Example output (the values are illustrative):

Organization                : example-org
Fine-grained PATs approved  : 42
  no_expiry                 : 3
  all_repositories          : 9
  write_or_admin            : 17
  unused_90d                : 11
Pending requests            : 4
SSO-authorized credentials  : 63
  broad_scope               : 21
  no_expiry                 : 8
Reports                     : ./pat-inventory

How to read the findings column:

  • no_expiry: the token never expires. Ask the owner to replace it with one that does, and set a lifetime policy in Step 2.
  • all_repositories: the token reaches every repository of the organization. Most automation needs a few.
  • write_or_admin and organization_permissions: the token can change code or settings. Confirm that each one still has an owner and a purpose.
  • unused_90d: no recorded use in 90 days, or none at all. Revoke these first (Step 4).
  • broad_scope: an SSO-authorized classic token with repo, admin:org, workflow or delete_repo. Move these to fine-grained tokens or a GitHub App.

Step 2: Set organization and enterprise token policies

Token policies decide which token types may reach the organization, whether fine-grained tokens need approval and how long tokens may live. Organization owners find them under Settings > Personal access tokens, with a tab per token type, as GitHub's organization policy article describes. The defaults below are GitHub's own (as of November 2026).

Setting Where (tab) Default Recommended value Effect
Require approval of fine-grained personal access tokens Settings > Fine-grained tokens Require administrator approval Keep Require administrator approval An owner approves each token before it reads private resources; owners' own tokens need no approval
Fine-grained personal access tokens (access policy) Settings > Fine-grained tokens Allowed Keep Allow access via personal access tokens Fine-grained tokens remain the approved, reviewable option
Restrict personal access tokens (classic) from accessing your organizations Settings > Tokens (classic) Allowed Restrict access via personal access tokens, after Step 1 shows who still uses them Classic tokens get 403; SSH keys created by tokens keep working; public resources stay readable
Set maximum lifetimes for personal access tokens (fine-grained) Fine-grained tokens tab 366 days A lifetime that matches your rotation cycle, for example 90 days Longer-lived tokens of members are blocked from the organization, not revoked
Set maximum lifetimes for personal access tokens (classic) Tokens (classic) tab No requirement Set a limit, for example 90 days Longer-lived tokens of members are blocked from the organization, not revoked

The 90 days are our starting point, not a GitHub value; pick a number your rotation process can meet. Change one setting at a time: approval and lifetime limits first, then the classic restriction once the inventory shows those tokens are replaced.

Enforce the same policies for the whole enterprise

On GitHub Enterprise Cloud, enterprise owners set the same controls on the enterprise's Personal access tokens pages, per token type, as the enterprise token policy article explains. The default, Allow organizations to configure access requirements, leaves the decision to each organization. Restrict access via personal access tokens or Allow access via personal access tokens applies to every organization, and organizations can't override it.

The approval policy offers Allow organizations to configure approval requirements (the default), Require approval and Disable approval. Organization owners can make the enterprise's maximum lifetime stricter for their own organization. The Exempt administrators checkbox keeps enterprise administrators out of the lifetime policy; GitHub suggests it when you use SCIM provisioning or have automation that hasn't moved to a GitHub App yet.

Step 3: Control classic tokens with SAML SSO authorization

On GitHub Enterprise Cloud with SAML single sign-on, a classic token can't reach the organization until its owner authorizes it for SSO, so SSO doubles as an inventory of classic tokens. Fine-grained tokens are authorized while they are created. GitHub's SSO authorization article lists the rules:

  • A member needs a linked external identity first, created by signing in through the identity provider at least once.
  • Once a member has a linked identity, only authorized tokens and SSH keys work with that organization, even if SSO isn't enforced.
  • An authorization lasts until an owner revokes it, the member leaves the organization, the token's scopes are edited or it is regenerated, or the token expires.

To review one member, open People, select the member, then SAML identity linked > Authorized credentials. GitHub shows only the last characters of each token or key. Revoke removes the SAML authorization, not the token or key itself. For many members at once, enterprise owners open the enterprise Settings > Authentication security page and, in the Danger zone, use Revoke for to remove SSO authorizations for one user, for one credential type or for all users, as GitHub's incident response article describes. That action covers every organization in the enterprise.

Step 4: Revoke and rotate tokens, and respond to a leak

Revoke a token as soon as nobody needs it or anyone else has seen it. For secret rotation, issue a new token before you delete the old one. GitHub can't restore an expired or revoked token, so plan for a replacement.

Revoke a fine-grained token's access to the organization

Owners revoke fine-grained tokens under Personal access tokens > Active tokens > the token > Revoke, or several at once with tokens selected... > Revoke.... The token's creator gets an email. A revoked token can still read public resources, and SSH keys it created keep working, so check the owner's SSH keys too.

The script below revokes by grant_id from the inventory report. It changes configuration only with --apply; without it, it makes a dry run that lists the matching grants. It needs an app with Personal access tokens at Read & write.

#!/usr/bin/env bash
#
# revoke-org-fine-grained-pat.sh
#
# Purpose:  Revoke the access that one or more fine-grained personal access
#           tokens have to a GitHub organization. Take the IDs from the
#           grant_id column of fine-grained-pats.csv (github-pat-inventory.sh).
# Mode:     Changes configuration, but only with --apply. Without --apply it
#           is a dry run: it sends GET requests only and lists the grants it
#           would revoke.
# Effect:   A revoked token can still read public resources, and SSH keys
#           created with it keep working. The token itself is not deleted.
# Auth:     Run gh with a GitHub App installation access token in GH_TOKEN.
#           The app needs the organization permission
#             Personal access tokens: Read & write
# Where:    Admin workstation or a GitHub Actions job with GitHub CLI (gh).
# Usage:    revoke-org-fine-grained-pat.sh <org> <grant-id>[,<grant-id>...] [--apply]
# Example:  revoke-org-fine-grained-pat.sh example-org 4100001,4100002
#           revoke-org-fine-grained-pat.sh example-org 4100001,4100002 --apply

set -euo pipefail

USAGE='usage: revoke-org-fine-grained-pat.sh <org> <grant-id>[,<grant-id>...] [--apply]'
ORG="${1:?$USAGE}"
IDS="${2:?$USAGE}"
APPLY=false
if [ "${3:-}" = "--apply" ]; then
  APPLY=true
elif [ -n "${3:-}" ]; then
  echo "Unknown option: $3" >&2
  exit 2
fi

if ! [[ "$ORG" =~ ^[A-Za-z0-9-]+$ ]]; then
  echo "The organization name may contain only letters, digits and hyphens." >&2
  exit 2
fi
if ! [[ "$IDS" =~ ^[0-9]+(,[0-9]+)*$ ]]; then
  echo "Grant IDs must be numbers separated by commas, for example 4100001,4100002." >&2
  exit 2
fi
command -v gh >/dev/null 2>&1 || { echo "GitHub CLI (gh) is not installed." >&2; exit 1; }

# 1. Show the grants that match (GET only)
echo 'grant_id,token_name,owner,repository_selection,token_last_used_at'
gh api --method GET --paginate "/orgs/${ORG}/personal-access-tokens" -f per_page=100 \
  --jq ".[] | select(.id as \$i | [${IDS}] | any(.[]; . == \$i)) | [.id, .token_name, .owner.login, .repository_selection, (.token_last_used_at // \"\")] | @csv"

if [ "$APPLY" != true ]; then
  echo "Dry run: nothing was revoked. Run again with --apply to revoke the grants listed above." >&2
  exit 0
fi

# 2. Revoke (POST, only with --apply)
fields=()
IFS=',' read -r -a id_list <<< "$IDS"
for id in "${id_list[@]}"; do
  fields+=(-F "pat_ids[]=${id}")
done

gh api --method POST "/orgs/${ORG}/personal-access-tokens" -f action=revoke "${fields[@]}" --silent
echo "Revocation requested for grant IDs ${IDS}. Run the inventory again to confirm." >&2

Run the dry run first and compare the list with the report:

bash revoke-org-fine-grained-pat.sh example-org 4100001,4100002
grant_id,token_name,owner,repository_selection,token_last_used_at
4100001,"old-deploy-script","dev-user-1","all","2026-01-12T08:40:05Z"
4100002,"release-notes-bot","dev-user-2","subset",""
Dry run: nothing was revoked. Run again with --apply to revoke the grants listed above.

Classic tokens can't be revoked from the organization's token pages. Revoke their SSO authorization (Step 3), restrict classic tokens (Step 2), or ask the owner to delete the token under Developer settings.

Respond to a leaked token

A leaked token is an incident, not a cleanup task. GitHub's revocation article covers the paths below.

  1. Revoke it now. The owner deletes it under Developer settings. Anyone who finds a token can submit it to GitHub's credential revocation API, which accepts ghp_ and github_pat_ tokens without authentication and notifies the owner.
  2. Cut its organization access. Revoke the fine-grained grant or the SSO authorization, as above.
  3. Find what it did. Audit log events record a SHA-256 hashed_token for actions taken outside the web interface. On GitHub Enterprise Cloud, search the enterprise audit log for hashed_token:"VALUE"; the credential inventory export holds the hash for classic tokens.
  4. Rotate. Generate a new credential, replace the old one everywhere it is stored, then delete the old one, as GitHub's remediation guidance says.
  5. Check what the token created. Look for SSH keys and deploy keys. Deleting a token that created a deploy key also deletes that deploy key, so plan the deployment change first.

GitHub also revokes tokens on its own. A valid personal access token pushed to a public repository or a public gist is revoked automatically, and a token that hasn't been used for a year is revoked as well.

Catch leaked tokens with secret scanning and push protection

Secret scanning finds known secret types in Git history, issues, pull requests and more. The GitHub Personal Access Token pattern supports user alerts, push protection and validity checks. As of November 2026, secret scanning runs free on public repositories; organization-owned private and internal repositories need GitHub Secret Protection on GitHub Team or GitHub Enterprise Cloud.

Push protection blocks a push that contains a detected secret. For users, it is on by default on GitHub.com and stops pushes of secrets to public repositories. For repositories, it needs Secret Protection and is off until a repository administrator, organization owner, security manager or enterprise owner enables it.

For repository push protection, anyone with write access can bypass a block by default by giving a reason, which creates an alert, an audit log event and an email. Delegated bypass narrows who can do that. When an alert fires, rotate the token first; removing it from Git history matters less once it is revoked.

Step 5: Replace personal access tokens with GitHub Apps, GITHUB_TOKEN and OIDC

A personal access token belongs to a person, so automation built on one acts with that person's rights and breaks when the person loses access. GitHub recommends a GitHub App for work on behalf of an organization and for long-lived integrations, and GITHUB_TOKEN inside Actions workflows.

Use case Replace the PAT with Why
A workflow that works in its own repository GITHUB_TOKEN with a permissions block Created for each job, limited to the repository, expires when the job ends
A workflow that needs other repositories or organization APIs A GitHub App installation token from actions/create-github-app-token Short-lived, permissions chosen per app, revoked at the end of the job by default
A service, bot or integration A GitHub App Not tied to a user, uses no seat, stays installed when the person who installed it leaves
A deployment to AWS, Azure or Google Cloud OIDC from GitHub Actions The cloud issues a short-lived token per job; no cloud secret is stored in GitHub
A person at the command line GitHub CLI or Git Credential Manager No token to copy into files

Two settings make the switch stick. Set the organization's Settings > Actions > General > Workflow permissions to read access for the contents and packages permissions, which is the default for new organizations. Then give each workflow only the permissions it needs; permissions: {} turns all of them off.

The GITHUB_TOKEN lives at most six hours on GitHub-hosted runners, the maximum job time. On self-hosted runners it can be refreshed for no more than 24 hours. A GitHub App's own credential, its private key, is now the secret to protect; keep it in an Actions secret of the one repository that runs the workflow.

For cloud deployments, the guides on replacing GCP service account keys and retiring AWS IAM users cover the cloud side of workload identity federation.

Verify

Check the policies, the inventory and a real request after each change.

Check Expected result
Rerun github-pat-inventory.sh no_expiry and unused_90d drop toward 0; every write_or_admin row has a known owner
Settings > Personal access tokens, both tabs The approval, restriction and lifetime choices from Step 2 are saved
A test member's classic token against a private organization repository, after the restriction A 403 response
A test member's new fine-grained token for the organization Status pending until an owner approves it under Pending requests
github-pat-audit-events.sh for the change date A policy event for each change you made, with you as the actor
The security settings of the repositories in scope Secret scanning and push protection show as enabled

Roll back

Policy changes are reversible in the same settings pages, but revoked and deleted tokens can't be restored.

Change How to roll back Notes
Classic token restriction Select Allow access via personal access tokens on the Tokens (classic) tab Use this only to unblock a critical script while you replace its token
Approval requirement Select Do not require administrator approval Tokens of members then reach private resources without review
Maximum lifetime Raise the limit; enterprise owners can also remove it Blocked tokens can reach the organization again; the policy revoked nothing
Enterprise policy Select Allow organizations to configure access requirements Each organization decides for itself again
Revoked fine-grained token access Can't be undone GitHub can't restore a revoked token; the owner creates a new token and requests organization access again
Revoked SSO authorization The member creates a new token and authorizes it with Configure SSO GitHub's incident response article says a revoked credential can't be authorized again for that organization; needs an active linked identity
Deleted or expired token Can't be undone GitHub can't restore an expired or revoked token; issue a new one

Keep the Step 1 reports as the record of which tokens existed before the change.

Monitor and detect

Watch the organization's GitHub audit log for new token grants, token policy changes and credential authorizations; GitHub's audit log event reference lists every action and its fields. The audit log keeps 180 days of events; Git events, where available, stay for only 7 days. To keep them longer and send them to a SIEM, enterprise owners on GitHub Enterprise Cloud set up audit log streaming, which carries events from the moment it is enabled.

Audit log action What it means Related pages
personal_access_token.access_granted A fine-grained token was granted access to organization resources Token granted organization access rules
personal_access_token.request_created A member created a fine-grained token that waits for approval Read it with the grant or denial that follows
personal_access_token.access_restriction_disabled The token restriction was turned off Same rules, which also cover weakened token policies
auto_approve_personal_access_token_requests.enable Fine-grained tokens no longer need approval Same rules
personal_access_token.expiration_limit_unset A maximum token lifetime was removed Same rules
org_credential_authorization.grant A member authorized a token or SSH key for SSO The token rules above; SSO disabled or identity provider changed rules watch the SSO setup itself
secret_scanning_push_protection.bypass A user pushed a detected secret past push protection Secret scanning or push protection disabled rules

GitHub's reference also lists personal_access_token.auto_approve_grant_requests_enabled and _disabled for the approval setting. Its descriptions run against the names: auto_approve_grant_requests_disabled is the event for tokens that reach organization resources without prior approval, and auto_approve_grant_requests_enabled is the event for the organization requiring approval. Alert on both actions, so a change in either direction gets reviewed. Users can see their own token activity, such as personal_access_token.create, in their account's security log.

The token rule pages carry Sigma rules with Splunk, Microsoft Sentinel and QRadar queries. Pair a grant with bulk repository cloning, and alert when someone deletes or pauses the audit log stream. New GitHub App or OAuth app installations and Actions secret changes deserve the same review, because they are where replacement credentials live. So does a weaker default GITHUB_TOKEN permission, which undoes the Step 5 setting.

To pull the same events on demand, the read-only script below queries the audit log REST API, which needs GitHub Enterprise Cloud. It runs as an organization owner with the read:audit_log scope, or with an installation token whose app has Administration at Read-only.

#!/usr/bin/env bash
#
# github-pat-audit-events.sh
#
# Purpose:  List personal access token events from an organization's audit
#           log since a date: token requests, grants and revocations, token
#           policy changes and SSO credential authorizations. Prints CSV to
#           standard output.
# Mode:     Read-only. Sends GET requests to the audit log API only.
# Auth:     GitHub Enterprise Cloud. Run gh as an organization owner whose
#           token (classic) has the read:audit_log scope, or with a GitHub App
#           installation access token in GH_TOKEN whose app has the
#           Administration organization permission (Read-only).
# Where:    Admin workstation or a GitHub Actions job with GitHub CLI (gh).
# Usage:    github-pat-audit-events.sh <org> <since YYYY-MM-DD>
# Example:  github-pat-audit-events.sh example-org 2026-11-01 > pat-events.csv

set -euo pipefail

USAGE='usage: github-pat-audit-events.sh <org> <since YYYY-MM-DD>'
ORG="${1:?$USAGE}"
SINCE="${2:?$USAGE}"

if ! [[ "$ORG" =~ ^[A-Za-z0-9-]+$ ]]; then
  echo "The organization name may contain only letters, digits and hyphens." >&2
  exit 2
fi
if ! [[ "$SINCE" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
  echo "The start date must use the YYYY-MM-DD format." >&2
  exit 2
fi
command -v gh >/dev/null 2>&1 || { echo "GitHub CLI (gh) is not installed." >&2; exit 1; }

echo 'created_utc,action,actor,user,token_name,org'
for category in personal_access_token auto_approve_personal_access_token_requests org_credential_authorization; do
  gh api --method GET --paginate "/orgs/${ORG}/audit-log" \
    -f phrase="action:${category} created:>=${SINCE}" -f per_page=100 \
    --jq '.[] | [((.created_at // .["@timestamp"]) / 1000 | floor | todate), .action, (.actor // ""), (.user // ""), (.user_programmatic_access_name // ""), (.org // "")] | @csv'
done
bash github-pat-audit-events.sh example-org 2026-11-01 > pat-events.csv
created_utc,action,actor,user,token_name,org
"2026-11-24T10:02:17Z","personal_access_token.request_created","dev-user-2","","release-notes-bot","example-org"
"2026-11-24T10:31:40Z","personal_access_token.access_granted","org-owner-1","","release-notes-bot","example-org"
"2026-11-25T08:12:03Z","org_credential_authorization.grant","dev-user-3","","","example-org"

The REST API allows 1,750 audit log queries per hour per user and IP address, so schedule large exports instead of running them in a loop.

Troubleshooting

Most token problems come from a policy doing its job or from the wrong kind of credential calling an endpoint.

Symptom Cause Fix
A classic token gets 403 on organization resources The organization restricts classic tokens Use a fine-grained token, a GitHub App or an OAuth app
The organization is missing under Resource owner The organization blocks fine-grained tokens Ask an owner which credential the organization allows
A new fine-grained token reads only public data The request is pending approval An owner approves it under Pending requests
API calls start failing after a lifetime policy The token's lifetime exceeds the limit Regenerate the token with a compliant lifetime
A classic token fails in an SSO organization It isn't authorized for SSO Configure SSO > Authorize; sign in through the identity provider once first
gh api /orgs/example-org/personal-access-tokens fails with your PAT These endpoints accept only GitHub App tokens Use a GitHub App installation token in GH_TOKEN
The audit log API returns an error It needs GitHub Enterprise Cloud, an owner and read:audit_log Check the plan, the role and the token scope
A token stopped working and nobody revoked it It expired, sat unused for a year, or was pushed to a public repository Create a new token and find out where the old one leaked
A push is blocked Push protection detected a secret Remove the secret from the commits; bypass only with a reason

How Forestall helps

Forestall scans GitHub organizations with its GitHub Assessment module, which checks vulnerabilities, misconfigurations and access relationships across users, teams, repositories, organization roles and app installations, and its Tier0 Analysis calculates attack paths to Tier 0 users and teams. It models the organization owner role as the GH_OWNER edge, a terminal attack path: an attacker who compromises an owner account, for example through a leaked personal access token, gains organization-wide administrative access. Forestall's own GitHub connection works with a read-only GitHub App or a PAT and recommends the app for larger deployments. The non-human and agent identity compromise use case shows how Forestall finds automation identities and what they can reach.

Frequently Asked Questions

How do I create a GitHub personal access token?

To create a GitHub personal access token, open Settings > Developer settings > Personal access tokens > Fine-grained tokens and select Generate new token. Name it, set an expiration, choose the resource owner, select Only select repositories, add the minimum permissions and select Generate token. If the organization requires approval, the token stays pending, and reads only public data, until an organization owner approves it. GitHub recommends fine-grained tokens over classic ones whenever possible.

Where do I find my GitHub personal access token?

Your GitHub personal access tokens are listed under Settings > Developer settings > Personal access tokens, split into Fine-grained tokens and Tokens (classic). From there you can delete a token, and you can update or regenerate a fine-grained one. If you no longer have the token's value, create a new token, update every place that uses it, then delete the old one.

Should I use a fine-grained or a classic personal access token?

Use a fine-grained personal access token whenever it can do the job. It is limited to one user or organization, to the repositories you choose and to specific permissions, and organization owners can require approval and see it. A classic token reaches every repository you can access through broad scopes. Keep classic tokens for the gaps GitHub lists, such as outside collaborator access, Packages or several organizations at once.

How long does a GitHub personal access token last?

A GitHub personal access token lasts until the expiration date you set, unless someone revokes it first. Fine-grained tokens allow infinite lifetimes, but organizations cap them at 366 days by default; classic tokens have no expiration requirement. GitHub also revokes a token that hasn't been used for a year and any valid token pushed to a public repository or gist. Set the shortest expiration that fits the task.

Can organization owners see and revoke members' personal access tokens?

Organization owners can see and revoke the fine-grained personal access tokens that reach the organization under Settings > Personal access tokens > Active tokens. Revoking removes the token's organization access but doesn't delete it. Owners can't list classic tokens there; on GitHub Enterprise Cloud with SAML SSO they can review and revoke the SSO authorizations of classic tokens, or restrict classic tokens for the whole organization.

What should I do if a GitHub personal access token leaks?

Revoke a leaked personal access token at once: delete it in the owner's developer settings, or submit it to GitHub's credential revocation API, which needs no authentication. Then remove its organization access, search the audit log for its hashed_token to see what it did, check for SSH keys or deploy keys it created, and issue a replacement with the least privilege. Turn on push protection to stop the next leak.

References

Share This Article, Secure Your Friends!

See your identity exposure clearly.

Start with a 1-day Proof of Value in your own environment.