Developers regularly use GitHub from their local machines to clone repositories, create branches, review pull requests, manage issues, and automate development tasks. Most of these activities require authentication, and many developers use personal access tokens or SSH keys to connect their tools to GitHub.

The challenge is that authentication credentials often remain available on a workstation for a long time. A token created for a temporary development task may continue working months later. If the workstation is compromised, a token is accidentally copied into a script, or a developer shares terminal output containing credentials, an attacker may gain access to repositories and other GitHub resources.

Short-lived authentication tokens help reduce this risk. Instead of depending on a long-lived credential, developers can authenticate through supported tools that obtain temporary access tokens and refresh them when necessary.

GitHub CLI provides a convenient way to use this approach from developer workstations. GitHub Apps also support short-lived user access tokens and installation access tokens for applications that need controlled access to GitHub resources.

In this article, we will explore why long-lived credentials create security risks, how short-lived GitHub authentication works, and how developers can configure their local environments to use temporary credentials safely.

Understanding GitHub Authentication From a Developer Workstation

A developer workstation may use several tools to communicate with GitHub:

  • Git for cloning, pulling, and pushing repositories.

  • GitHub CLI for managing pull requests, issues, and releases.

  • IDE extensions for repository management.

  • Scripts that call GitHub REST or GraphQL APIs.

  • Local development tools that automate repository operations.

Each tool needs an authentication mechanism.

For example, a developer might use a personal access token to authenticate Git operations over HTTPS. The token can also be used by scripts that call GitHub APIs.

A typical configuration might look like this:

Code
git clone https://github.com/example/OrderService.git

Git prompts for credentials or obtains them through a configured credential helper.

The problem is not that personal access tokens are inherently unsafe. The problem is how they are created, stored, shared, and maintained.

A long-lived token can remain valid even after the original development task is complete. Developers may forget where they used it, which applications have access to it, or whether it has been copied into local configuration files.

Consider a developer who creates a token with access to multiple repositories. The developer uses it for a small automation script and stores it in a local environment variable. Several months later, the script is no longer used, but the token remains active.

If the token is exposed through a terminal recording, debugging output, malware, or an accidentally committed configuration file, the attacker may continue using it until the credential is revoked or expires.

Short-lived authentication reduces the time during which an exposed credential can remain useful.

Understanding Short-Lived GitHub Tokens

GitHub supports several credential types, and their lifetimes are different.

The following table provides a practical comparison.

Credential type

Typical lifetime

Usage

Personal access token (classic)

Long-lived, based on configured expiration

User-level API and Git access

Fine-grained personal access token

Configurable expiration

Restricted access to selected repositories and permissions

GitHub App user access token

Eight hours by default when expiration is enabled

API operations on behalf of a user

GitHub App installation access token

One hour

API operations as an app installation

GitHub Actions GITHUB_TOKEN

Workflow job duration

Operations inside a workflow

The important distinction is that short-lived tokens expire automatically.

For example, GitHub App installation access tokens normally remain valid for one hour. A GitHub App user access token expires after eight hours by default when the expiration feature is enabled.

These tokens are not interchangeable. An installation token represents an application installation, while a user access token represents an application acting with a user's authorization.

For local development, GitHub CLI offers another useful option: expiring credentials that it can refresh automatically when supported by the authentication flow and host configuration.

Using GitHub CLI for Short-Lived Authentication

GitHub CLI is one of the simplest ways to manage GitHub authentication from a developer workstation.

Instead of manually generating and copying personal access tokens, developers can authenticate through an interactive browser-based process.

Install GitHub CLI using the installation method appropriate for the operating system.

After installation, run:

Code
gh auth login

Follow the prompts to select the GitHub host and authentication method.

For GitHub.com, the browser-based authentication process allows the developer to authorize the CLI without manually copying a long-lived token into a script.

GitHub CLI stores credentials in the operating system's credential store when one is available. If a suitable credential store is unavailable or cannot be used, the CLI may fall back to a plain-text configuration file.

This fallback matters on developer machines. Teams should ensure that workstations have an appropriate credential store configured and avoid assuming that every operating system installation provides the same level of credential protection.

Requesting Expiring Credentials

GitHub CLI supports the --expiring option for authentication:

Code
gh auth login --expiring

This tells GitHub CLI to prefer expiring credentials where the GitHub host and authentication configuration support them.

It is a preference rather than a guarantee. The host must support the relevant expiring credential behavior, and the OAuth application configuration must allow it.

Developers can also configure GitHub CLI to prefer expiring credentials by default:

Code
gh config set expiring_credentials true

To inspect the current authentication status, run:

Code
gh auth status

The command reports the authenticated account and host information. It can also provide token expiration details without displaying the actual token.

Avoid using the --show-token option during ordinary troubleshooting because it prints the active credential.

Refreshing Authentication Credentials

Expiring credentials are useful only when the developer can renew them safely.

GitHub CLI supports automatic refresh for supported expiring credentials. When a command needs authentication and the stored access token has expired or is close to expiration, the CLI can refresh it using the associated refresh credential.

For example:

Code
gh api user

This command retrieves information about the currently authenticated user.

The developer does not need to manually generate a replacement token every time the access token expires.

GitHub CLI also provides an authentication refresh command:

Code
gh auth refresh --expiring

This can be used when updating authentication permissions while retaining the preference for expiring credentials.

When using expiring credentials for Git operations, Git 2.46 or newer is recommended. Older versions may not correctly honor the non-cacheable credential information provided by GitHub CLI, which can result in a credential helper retaining an expired token.

Using GitHub CLI Credentials With Git Operations

A common developer requirement is authenticating both Git and GitHub CLI.

For example, a developer may use Git to push code and GitHub CLI to create a pull request.

GitHub CLI can configure Git to use its authentication mechanism:

Code
gh auth setup-git

After configuration, Git can use the credentials managed by GitHub CLI for supported HTTPS operations.

A developer can then work with a repository:

Bash
git clone https://github.com/example/OrderService.git

cd OrderService

git checkout -b feature/order-validation

git add .

git commit -m "Add order validation"

git push -u origin feature/order-validation

The authentication process is handled through the configured credential integration instead of requiring developers to paste a personal access token into every Git command.

This approach is particularly useful for teams that want to standardize local GitHub authentication without introducing custom token-management scripts.

Using GitHub CLI Authentication in Local Scripts

Some development scripts need to call GitHub APIs.

A common mistake is creating a separate personal access token for every script and storing it in a local configuration file.

GitHub CLI already manages authentication for the current user. A script can use its active token when required.

For example, a Bash script can retrieve the token and pass it to an API client:

Bash
#!/usr/bin/env bash

set -euo pipefail

TOKEN=$(gh auth token)

if [ -z "$TOKEN" ]; then
    echo "GitHub authentication is unavailable."
    exit 1
fi

curl --fail --silent --show-error \
    -H "Authorization: Bearer $TOKEN" \
    -H "Accept: application/vnd.github+json" \
    https://api.github.com/user

This example demonstrates how to reuse GitHub CLI authentication rather than maintaining another token.

However, retrieving a token through gh auth token exposes it to the script's process environment and memory. The token should never be printed, written to a log, or saved in a temporary file without a specific security requirement.

For scripts that can use GitHub CLI directly, prefer commands such as gh api instead:

Code
gh api user

This avoids manually handling the token in the script.

When a script needs an environment variable, GitHub CLI also supports GH_TOKEN for non-interactive use:

Code
GH_TOKEN="$TOKEN" gh api user

For a long-running script, remember that a token obtained at the beginning may expire while the script is running. Where possible, use GitHub CLI commands that manage refresh behavior rather than retaining a copied token for the entire process.

Using GitHub Apps for More Controlled Authentication

GitHub CLI works well for individual developer authentication. However, some development tools need access to repositories on behalf of an application rather than a specific user.

For example, an internal developer portal might need to:

  • Read repository metadata.

  • Create branches.

  • Inspect pull requests.

  • Add comments to issues.

  • Read workflow information.

  • Update selected repository settings.

Creating a personal access token for a shared internal tool is usually a poor design. The token belongs to an individual user, and the tool may continue using that user's permissions even when the user changes teams or leaves the organization.

A GitHub App provides a better application-level authentication model.

A GitHub App can receive permissions for specific repository operations and can be installed on selected repositories or organizations.

When an application needs to perform an operation, it can generate an installation access token.

The general flow is:

  1. A GitHub App is registered and assigned the minimum required permissions.

  2. The organization installs the application on selected repositories.

  3. The application authenticates using its private key.

  4. The application requests an installation access token.

  5. GitHub returns a short-lived token.

  6. The application uses the token for permitted API operations.

  7. The token expires automatically, and the application requests another when needed.

Installation access tokens normally expire after one hour.

This approach separates application identity from developer identity and makes repository access easier to control.

Generating an Installation Access Token

A GitHub App uses its private key to create a JSON Web Token (JWT). The JWT is then used to request an installation access token.

The following Python example shows the basic structure of the request. It assumes that the application has already generated a valid JWT and obtained the installation ID.

Python
import requests

app_jwt = "GENERATED_APP_JWT"
installation_id = "12345678"

url = (
    "https://api.github.com/app/installations/"
    f"{installation_id}/access_tokens"
)

headers = {
    "Accept": "application/vnd.github+json",
    "Authorization": f"Bearer {app_jwt}",
    "X-GitHub-Api-Version": "2022-11-28"
}

response = requests.post(
    url,
    headers=headers,
    json={}
)

response.raise_for_status()

token_data = response.json()

installation_token = token_data["token"]
expires_at = token_data["expires_at"]

print(f"Token expires at: {expires_at}")

The example deliberately does not print the installation token.

The JWT generation process and private-key handling are important parts of a production GitHub App implementation. The private key must be stored securely, and the JWT must be generated with the correct application identity and time claims.

The application should also avoid requesting broader repository access than its operations require.

User Access Tokens and Installation Tokens

GitHub Apps can also generate user access tokens when an application needs to act on behalf of an individual user.

These tokens have different permission and access behavior from installation tokens.

A user access token can only access resources that both the application and the user are permitted to access. This prevents an application from gaining access to resources merely because the application itself has broader permissions.

User access tokens expire after eight hours by default when expiration is enabled. A refresh token can be used to obtain a new access token.

Choose the credential type based on the actual requirement:

Requirement

Suitable authentication

Developer working with GitHub from a terminal

GitHub CLI

Local script using the developer's GitHub identity

GitHub CLI authentication

Internal service accessing installed repositories

GitHub App installation token

Application acting on behalf of an individual developer

GitHub App user access token

Workflow accessing GitHub during a job

GITHUB_TOKEN

Protecting Tokens on Developer Workstations

Short-lived tokens reduce exposure time, but they still need secure storage and careful handling.

A compromised workstation can expose credentials regardless of their expiration period. Developers should therefore follow a few basic security practices.

Use the Operating System Credential Store

GitHub CLI normally stores credentials in the operating system's credential store when available.

This is preferable to manually writing tokens into shell scripts, project configuration files, or plain-text documents.

Avoid enabling insecure credential storage unless there is a specific, reviewed reason to do so.

Also check how Git credential helpers behave on the workstation. A helper that caches credentials for longer than their intended lifetime can weaken the benefits of expiring tokens.

Avoid Printing Tokens

Never use commands that expose the active token during normal troubleshooting.

For example, avoid:

Code
gh auth token

when the terminal output may be captured, shared, or recorded.

Use the following command instead:

Code
gh auth status

It provides useful authentication information without displaying the token by default.

The same principle applies to environment variables. Avoid dumping the complete environment with commands such as printenv when authentication credentials may be present.

Use the Minimum Required Permissions

A token should have only the permissions needed for its task.

For example, a local tool that reads repository metadata should not receive write access to repository contents.

For GitHub Apps, configure repository permissions carefully and install the app only on repositories it needs.

For personal access tokens, prefer fine-grained permissions and selected repository access when a personal access token is genuinely required.

Avoid Storing Tokens in Project Files

Do not store credentials in:

  • Source code.

  • .env files committed to Git.

  • Application configuration checked into a repository.

  • Shell scripts.

  • Shared developer documentation.

  • Local build artifacts that are synchronized or uploaded.

If a local tool needs a credential, obtain it through a supported authentication mechanism rather than embedding it in the project.

Handling Token Expiration and Authentication Failures

Short-lived credentials introduce an operational requirement: applications and scripts must handle expiration correctly.

A common failure occurs when a developer starts a long-running operation with a token that expires before the operation finishes.

For example, a local script might start a repository analysis process and use the same token for every API request. If the token expires during execution, subsequent requests may return an HTTP 401 Unauthorized response.

A reliable implementation should distinguish authentication failures from permission failures and network problems.

Error

Possible cause

Recommended action

HTTP 401

Token expired or revoked

Refresh or reauthenticate

HTTP 403

Missing permission, policy restriction, or rate limit

Inspect permissions and response details

HTTP 404

Resource does not exist or is not accessible

Verify repository access and resource name

Credential helper failure

Local credential storage problem

Check Git and operating system credential configuration

Refresh failure

Refresh credential expired or authorization revoked

Complete the authentication process again

Do not respond to every authentication error by creating a new personal access token. First determine whether the problem is expiration, insufficient permissions, organization policy, or revoked authorization.

For GitHub CLI, developers can inspect the current authentication state:

Code
gh auth status

If the credentials need to be refreshed or additional permissions are required, use the supported authentication refresh process:

Code
gh auth refresh --expiring

If the authorization has been revoked, the developer may need to authenticate again.

Common Mistakes When Using Short-Lived Tokens

Short-lived authentication is not automatically secure. Several implementation mistakes can reduce its benefits.

Treating Every Token as Short-Lived

Not all GitHub credentials expire automatically. Personal access tokens can remain valid for a configured period, and some credential types may be configured without expiration.

Always verify the credential type and its actual expiration behavior instead of assuming that every token returned by a GitHub tool is temporary.

Copying Temporary Tokens Into Scripts

A developer might retrieve an expiring token and save it in a configuration file for convenience.

This creates another credential storage location and can make expiration handling difficult.

Prefer GitHub CLI commands or a proper credential integration that can refresh credentials when needed.

Giving Local Tools Excessive Permissions

A tool that only reads pull request information should not receive permission to modify repository contents.

Excessive permissions increase the impact of a compromised workstation or malicious local process.

Ignoring Credential Storage Fallbacks

GitHub CLI can fall back to plain-text storage when an operating system credential store is unavailable or cannot be used.

Developers should understand where credentials are stored on their machines and ensure that local configuration directories are protected.

Assuming Expiration Prevents Credential Theft

A stolen token can still be used until it expires or is revoked.

Short-lived tokens reduce the useful lifetime of an exposed credential, but they do not replace endpoint security, access controls, or credential revocation procedures.

Teams should define a consistent authentication strategy for local development rather than allowing every developer to create and store credentials differently.

A practical approach is to use GitHub CLI for normal developer operations, short-lived credentials where supported, and GitHub Apps for internal tools that need application-level access.

The following approach works well for many development teams:

Development activity

Recommended approach

Cloning and pushing repositories

GitHub CLI with Git credential integration

Creating pull requests and managing issues

GitHub CLI

Local scripts calling GitHub APIs

GitHub CLI authentication

Internal repository automation

GitHub App installation tokens

Tools acting on behalf of users

GitHub App user access tokens

Automated GitHub Actions workflows

Restricted GITHUB_TOKEN

Cloud deployment from workflows

OpenID Connect where supported

Organizations should also review credential policies periodically, remove unused authorizations, and provide clear instructions for developers who change machines or leave the organization.

Summary

Long-lived authentication credentials create unnecessary risk on developer workstations. A token that remains active for months can expose repositories and organization resources if it is accidentally shared or stolen.

GitHub CLI provides a convenient way to authenticate from local machines and supports expiring credentials that can refresh automatically when the host and configuration allow it. Developers can use the same authentication for Git operations and local scripts without maintaining separate personal access tokens.

For internal applications, GitHub Apps provide a more controlled approach through installation and user access tokens with defined permissions and expiration behavior.

The best strategy is to use the correct credential type for each task, store credentials in secure locations, avoid printing or copying tokens, and grant only the permissions required. Short-lived tokens do not eliminate every authentication risk, but when combined with secure workstation practices and least-privilege access, they significantly improve how developers manage GitHub authentication.