Skip to main content

Module credentials

Module credentials 

Source
Expand description

Credential retrieval for Claude Code OAuth tokens.

This module provides platform-specific credential retrieval:

  • macOS: Reads from Keychain
  • Linux: Reads from ~/.claude/.credentials.json

§Token Lifecycle

Claude Code OAuth tokens have a limited validity period:

PropertyValue
Token typeOAuth access token
Validity8 hours from issuance
RefreshAutomatic by Claude Code CLI
StoragePlatform keychain / credential file

§Token Rotation

Tokens are rotated approximately every 8 hours. When a token expires:

  1. If Claude Code is running: It automatically refreshes the token using the refresh token stored alongside the access token.

  2. If Claude Code is not running: The token will be expired when you next try to use it. Running claude will trigger a refresh.

§Error Handling for Expired Tokens

This crate returns CredentialError::Expired when:

  • The expiresAt timestamp in the credential JSON is in the past

The API returns ApiError::Unauthorized when:

  • The token was valid locally but rejected by the server
  • This can happen if the token was revoked or if clocks are out of sync
use claude_usage::{get_usage, Error, CredentialError, ApiError};

match get_usage() {
    Ok(usage) => { /* success */ }
    Err(Error::Credential(CredentialError::NotFound)) => {
        // User hasn't logged in with Claude Code
        eprintln!("Run `claude` to login first");
    }
    Err(Error::Credential(CredentialError::Expired)) => {
        // Token expired locally - needs refresh
        eprintln!("Token expired. Run `claude` to refresh");
    }
    Err(Error::Api(ApiError::Unauthorized)) => {
        // Token rejected by server - may be revoked or clock skew
        eprintln!("Token invalid. Run `claude` to re-authenticate");
    }
    Err(e) => eprintln!("Error: {}", e),
}

§Security

Tokens are retrieved, used immediately, and discarded. They are never:

  • Logged
  • Stored in memory longer than necessary
  • Passed to other modules

Constants§

ENV_VAR_TOKEN
Environment variable that can override file-based credentials.
KEYCHAIN_SERVICE
Service name used by Claude Code in macOS Keychain.
LINUX_CREDENTIALS_PATH
Path to credentials file on Linux (relative to HOME).

Functions§

get_token
Retrieve the OAuth access token from platform-specific storage.