OAuth 2.0 in Zsh: Automating API Authentication from the Command Line
The terminal waited, blinking, ready for the next command. You type fast, but the network is guarded, and every request demands proof. OAuth 2.0 is that proof — a standard protocol for secure authorization. Zsh is your shell, fast and scriptable. Together, they can authenticate APIs without slowing you down.
OAuth 2.0 in Zsh means you can trigger token requests right from your command line, parse responses, and pass credentials into curl or httpie without context switching. No browser tabs. No manual copy‑paste. The flow is automated: request token, store token, use token. In long-running scripts or CI pipelines, it reduces friction and risk.
To start, generate your OAuth 2.0 client credentials from the provider’s developer console. You will need a client_id, client_secret, authorization_endpoint, and token_endpoint. Store them in environment variables inside .zshrc:
export OAUTH_CLIENT_ID="your-client-id"
export OAUTH_CLIENT_SECRET="your-client-secret"
export OAUTH_AUTH_URL="https://provider.com/oauth2/auth"
export OAUTH_TOKEN_URL="https://provider.com/oauth2/token"
Then, create a Zsh function to request and cache the access token:
oauth_token() {
local response=$(curl -s -X POST $OAUTH_TOKEN_URL \
-d "client_id=$OAUTH_CLIENT_ID"\
-d "client_secret=$OAUTH_CLIENT_SECRET"\
-d "grant_type=client_credentials")
echo $response | jq -r '.access_token'
}
You can call oauth_token inside scripts to inject the latest token:
curl -H "Authorization: Bearer $(oauth_token)"https://api.example.com/data
Advanced workers use Zsh’s associative arrays to store multiple service tokens, or fzf for choosing which API to authenticate. You can combine this with OAuth 2.0’s refresh tokens to avoid hitting the login endpoint repeatedly.
Security matters. Keep .zshrc secrets safe by setting file permissions chmod 600 ~/.zshrc. Prefer environment variables over hard‑coded values. Log minimally and never print tokens to stdout unless essential.
When OAuth 2.0 meets Zsh, you control the authentication handshake from a single terminal window. Less clicking. More building. Integrations that once took hours shrink to minutes.
See it live with hoop.dev — run your OAuth 2.0 Zsh workflow end‑to‑end in minutes. Build faster. Authenticate smarter.