Overview
Rancher uses token-based authentication for all API requests. Tokens are stored as Kubernetes custom resources (Token CRD) and provide flexible authentication for both interactive users and API clients.
All token management is handled by the Token Manager in pkg/auth/tokens/.
Token Architecture
Token Structure
Rancher tokens consist of two parts:- Token Name: Kubernetes resource name (stored in etcd)
- Token Key: Secret authentication value (hashed when stored)
token-abcd1:z9x8y7w6v5u4t3s2r1q0
Token Resource
Tokens are stored asToken custom resources:
Token Types
Session Tokens (Login Tokens)
Purpose: Interactive user sessions (web UI) Characteristics:- Created during login flow
- Stored in HTTP-only cookie (
R_SESS) - Associated with authentication provider
- Contains user principal and groups
- Default TTL: 16 hours (configurable)
- Not marked as derived
- Labeled with
kind: session
- User authenticates with provider
- Token Manager creates session token
- Token key hashed using SHA3-512
- Token stored in Kubernetes
- Cookie set with token value
- Token validated on each request
- Deleted on logout or expiration
Derived Tokens (API Tokens)
Purpose: Programmatic API access Characteristics:- Created from existing session token
- Not tied to cookie
- User explicitly creates via API
- Optional custom description
- Optional custom TTL (up to max)
- Marked as
isDerived: true - Inherits user context from parent
- CI/CD pipelines
- Automation scripts
- Third-party integrations
- Service accounts
- Mobile applications
Kubeconfig Tokens
Purpose: kubectl access to downstream clusters Characteristics:- Created for generated kubeconfig files
- Cluster-scoped (specific to one cluster)
- Auto-generated name:
kubeconfig-{username}.{clusterid} - Default TTL from setting:
kubeconfig-default-token-ttl-minutes - Labeled with
kind: kubeconfig - Marked as derived
- Expiration set on creation
System Tokens
Purpose: Internal Rancher services Characteristics:- Pre-defined token names (no random generation)
- No TTL (never expire)
- Specific user context
- Cannot be deleted via API
- Used by Rancher agents and controllers
Token Hashing
Overview
Token hashing protects authentication tokens by storing only cryptographic hashes, not the original token values. This feature is controlled by theTokenHashing feature flag.
Location: pkg/auth/tokens/hashers/
Supported Hash Algorithms
Rancher supports multiple hash algorithms for backwards compatibility:SHA3-512 (Current Default)
File:pkg/auth/tokens/hashers/sha3.go
Algorithm: SHA3-512 with random salt
Format: $3:salt:hash
Characteristics:
- Modern cryptographic standard
- 512-bit hash output
- Random 32-byte salt
- Fast verification
- Resistant to length extension attacks
SHA-256 (Legacy)
File:pkg/auth/tokens/hashers/sha256.go
Algorithm: SHA-256 with random salt
Format: $2:salt:hash
Characteristics:
- Legacy algorithm
- 256-bit hash output
- Still supported for existing tokens
- New tokens use SHA3
Scrypt (Legacy)
File:pkg/auth/tokens/hashers/scrypt.go
Algorithm: Scrypt key derivation
Format: $1:salt:hash
Characteristics:
- Original hashing algorithm
- Memory-hard function
- Slower verification (by design)
- Still supported for existing tokens
Hash Workflow
Token Creation:- Random token key generated (32 bytes)
- Token hashed using SHA3-512 with random salt
- Hash stored in
tokenfield:$3:salt:hash - Original token key returned to user once
- Annotation
authn.management.cattle.io/token-hashed: "true"added
- User presents token:
token-name:token-key - Token resource fetched by name
- Hash version extracted from stored hash
- Appropriate hasher selected
- Provided key hashed with same salt
- Hashes compared for equality
- Access granted on match
Migration
Existing unhashed tokens continue to work:- Old tokens stored as plaintext
- No automatic migration
- Hashing applied to new tokens only
- Verification detects hashed vs unhashed
Security Benefits
- Database Compromise: Attackers cannot use stolen hashes
- Backup Security: Backups don’t contain usable tokens
- Log Safety: Hashes safe to log
- Audit Trail: Original tokens never persisted
Token Lifecycle
Creation
Login Flow: API Token Creation:Validation
Per-Request Authentication:- Extract token from
Authorizationheader orR_SESScookie - Split into name and key components
- Look up token resource by name (with indexer for performance)
- Verify key matches stored hash
- Check token not expired (TTL)
- Check session not idle (last activity)
- Return user info and groups
- Index:
authn.management.cattle.io/token-key-index - Indexed value: hashed token key
- Allows cache lookup before client call
Expiration
Time-Based Expiration: Tokens expire based on TTL:ttlMillis: 0= No expiration (permanent)expiresAtfield set on creation- Checked on every authentication
- HTTP 410 Gone returned if expired
- Setting:
auth-user-session-idle-ttl-minutes - Last activity tracked in token
- Updated on authenticated requests
- Session expires if idle too long
- Only applies to session tokens, not derived tokens
- Setting:
auth-token-max-ttl-minutes - Applied when creating tokens
- User-requested TTL clamped to max
0= no limit
Deletion
Manual Deletion:- Current session token (use logout instead)
- Tokens belonging to other users
- System tokens
- Runs periodically in leader-elected instance
- Location:
pkg/auth/tokens/purge_daemon.go - Deletes tokens where
expiresAt < now - Cleans up orphaned token secrets
Token Management API
Location:pkg/auth/tokens/api.go
List User Tokens
Create Derived Token
Get Specific Token
Delete Token
Logout
Logout All
Token Authentication Methods
Bearer Token (Recommended)
Basic Authentication
Cookie Authentication
Used by web UI:Provider Secrets
Some authentication providers require per-user secrets for token refresh and group synchronization. Location:pkg/auth/tokens/manager.go
Providers with Secrets
These providers store per-user secrets:github- OAuth access tokenazuread- OAuth access tokengoogleoauth- OAuth access tokenoidc- Refresh tokenkeycloakoidc- Refresh token
Secret Storage
Namespace:cattle-system
Name: {userId}-secret
Structure:
Secret Lifecycle
Creation:- Secret created on first login with provider
- Access token from OAuth flow stored
- Used for subsequent group refresh
providerInfo if secret missing.
Update:
- Secret updated when token refreshed
- New access token replaces old
- Automatic cleanup when user deleted
- No manual deletion API
Token Security
Storage Security
- Hashed Keys: Token keys stored as SHA3-512 hashes
- Kubernetes Secrets: Token resources stored in etcd
- Encryption at Rest: Use Kubernetes encryption for etcd
- RBAC Protected: Token resources require authentication to access
Transmission Security
- HTTPS Only: Always use HTTPS in production
- HTTP-Only Cookies: Cookies not accessible to JavaScript
- Secure Cookie Flag: Cookies only sent over HTTPS
- CSRF Protection: Separate CSRF token for state changes
Token Scope
- User Context: Tokens tied to specific user
- Provider Context: Tokens linked to auth provider
- Cluster Scope: Optional cluster restriction
- Time Limit: TTL and idle timeout enforced
Best Practices
- Rotate Tokens: Regularly create new tokens and delete old
- Minimum TTL: Use shortest TTL practical for use case
- Separate Tokens: Different token per application/script
- Monitor Usage: Audit token usage in logs
- Delete Unused: Clean up tokens no longer needed
- Secure Storage: Never commit tokens to source control
- Kubeconfig Tokens: Use short TTL for kubeconfig tokens
Token Configuration
Settings
auth-token-max-ttl-minutes
- Maximum lifetime for any token
- Default: 0 (unlimited)
- Applies to session and derived tokens
- Admin can enforce organizational policy
kubeconfig-default-token-ttl-minutes
- Default TTL for kubeconfig tokens
- Default: 960 (16 hours)
- Applied when generating kubeconfig
- Can be overridden per request
auth-user-session-idle-ttl-minutes
- Session idle timeout
- Default: 0 (disabled)
- Only applies to session tokens
- Last activity tracked per request
Environment Variables
CATTLE_AUTH_API_BODY_LIMIT
- Limits request size for auth endpoints
- Default: 1Mi
- Protects against large payload attacks
Feature Flags
TokenHashing
- Enable/disable token hashing
- Default: Enabled
- Should always be enabled in production
- Only disable for debugging
Troubleshooting
Invalid Token
Error: HTTP 422 “invalid auth token value” Causes:- Token format incorrect (missing colon)
- Token key doesn’t match hash
- Token name doesn’t exist
- Token corrupted or truncated
- Check token format:
name:key - Verify token not modified
- Create new token if lost
Expired Token
Error: HTTP 410 “must authenticate, expired” Causes:- TTL exceeded
- Idle timeout exceeded
- Login again to get new token
- Increase TTL for API tokens
- Configure idle timeout appropriately
Token Not Found
Error: HTTP 404 “token not found” Causes:- Token deleted
- Token never created
- User deleted
- Create new token
- Verify user still exists
- Check token not auto-purged
Cannot Delete Token
Error: HTTP 400 “Cannot delete token for current session” Causes:- Attempting to delete active session token
- Use
/v3/tokens?action=logoutinstead - Or delete from different session
Hash Verification Failed
Error: Logs show “VerifyHash failed” Causes:- Token key doesn’t match stored hash
- Hash algorithm mismatch
- Token corrupted in database
- Create new token
- Check database integrity
- Verify TokenHashing feature flag consistent
Token Internals
Indexing
Tokens indexed for performance: User ID Index:- Label:
authn.management.cattle.io/token-userId - Used to: List all tokens for a user
- Query:
labelSelector=authn.management.cattle.io/token-userId={userId}
- Name:
authn.management.cattle.io/token-key-index - Indexed value: Hashed token key
- Used to: Fast token lookup during authentication
- Avoids client API call when cache hit
Token Constants
Token Accessor Interface
Tokens implement theaccessor.TokenAccessor interface:
See Also
- Authentication Overview - Authentication architecture
- Authentication Providers - Provider configuration
- RBAC - Authorization with tokens
- API Overview - Using tokens with API