State and authentication
Send a bearer token
Place an API token in the Authorization header and keep it out of source, logs, and command history.
Most APIs today authenticate with a bearer token. It’s a string you send in the Authorization header, prefixed with the word Bearer.
The name is literal. Whoever bears the token gets the access. No password prompt, no second factor, nothing else. So treat a token like a password, with whatever scope and lifetime the service gave it.
Sending the token is one line. Keeping it from leaking is the actual skill. That’s what this lesson is about.
Send the header
Read a disposable token from an environment variable:
export LAB_API_TOKEN='demo-token-for-practice'
curl --header "Authorization: Bearer $LAB_API_TOKEN" https://api.lab.test/profile
The shell expands the variable before curl runs, so the header arrives as Authorization: Bearer demo-token-for-practice. Notice the double quotes. Single quotes would send the literal text $LAB_API_TOKEN.
The token is not in the script file. That’s the point. Scripts get committed, and grepping a repository for Bearer finds leaked credentials more often than you’d think.
You can check the header reaches a server with a public echo endpoint:
curl --header "Authorization: Bearer $LAB_API_TOKEN" https://httpbin.org/bearer
The response is {"authenticated": true, "token": "demo-token-for-practice"}. That’s the exact header the server saw.
This check is useful when a real API returns 401 Unauthorized. If the echo shows the header intact, your curl command is fine. The problem is the token itself: expired, wrong scope, wrong environment.
Where tokens still leak
The environment variable keeps the token out of your script. It can still show up in other places. Know the escape routes:
- shell history, if you ever pasted the token literally
set -xin a script, which prints every expanded command, token includedcurl -v, which prints theAuthorizationheader- screenshots and pasted terminal output
Avoid all of these around real credentials. And don’t use a real token in this lab. The echo endpoint reflects the token back in plain text. That’s exactly what you never want happening to a credential that works somewhere.
When it leaks anyway
Revoke the token at the service and issue a new one. Rotating is cheap. Hoping nobody saw it is not a strategy.
I rotate any token that ended up in a terminal I shared on a call, even when I’m fairly sure nobody noticed. The five minutes it costs are nothing compared to the alternative.
Try it: export a fake token, send it to httpbin.org/bearer, then run the same command with -v and find the header in the > lines. Now you know exactly what verbose mode would reveal with a real one.
Lesson completed