C.W.K.
Stream
Lesson 05 of 06 · published

Tokens, Access, and CLI Login

~24 min · hub, auth

Level 0Scout
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Tokens are scoped, not all-powerful

HF user access tokens come in three scopes: read, write, and fine-grained. Read is enough to download public models, accept gated licenses, and call the Inference API. Write adds repo creation, push, and deletion. Fine-grained tokens (the modern default for service accounts) let you whitelist specific orgs and specific repos — you should be using these in any non-trivial CI setup.

Where the token lives

After huggingface-cli login the token is stored at ~/.cache/huggingface/token (override with HF_HOME). All clients (transformers, datasets, huggingface_hub, accelerate) read it from there. You can override per-process with the HF_TOKEN environment variable; this is the standard pattern in Docker images and CI.

Token rotation, the boring rule

Every token has a created-at timestamp and a last-used timestamp visible in huggingface.co/settings/tokens. If a token has been on a CI runner for > 90 days, rotate it. If a token has read scope and somehow ends up in a public repo, the blast radius is "you can download what they could already download" — but if it's a write token, that's a real incident. Rotate, audit pushes, and consider GitHub's secret scanning push protection.

Code

Login flows·bash
# Interactive — most common
huggingface-cli login

# Non-interactive (CI)
echo "${HF_TOKEN}" | huggingface-cli login --token "${HF_TOKEN}" --add-to-git-credential

# Confirm whoami
huggingface-cli whoami

# Token file location (default)
ls -l ~/.cache/huggingface/token
Token override priority·python
import os
from huggingface_hub import HfApi

# Priority: explicit token arg > HF_TOKEN env > ~/.cache/huggingface/token

# Explicit (highest priority — used in libraries that take a token kwarg)
api = HfApi(token=os.environ.get("HF_PROD_TOKEN"))
print(api.whoami())

# Implicit (env or cache)
api2 = HfApi()
print(api2.whoami())

External links

Exercise

Create a fine-grained token scoped to read-only on public repos, and another scoped to write on a single test repo you create ({your-username}/scratch-{date}). Verify both with whoami. Store them in a .env file. Push a README.md to the test repo using the write token, then try to push using the read token and observe the failure.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.