Python API Authentication and Secrets
Getting a token into a request is one line. Keeping it out of your source, your logs, your process list and your bug reports is the actual work. This guide sends the header, then demonstrates five ways the token escapes anyway - including one that is urllib3's doing rather than yours - and builds the logging filter that stops it, starting from a version that looked right and raised on every line.
APIs and Cloud Guide 25 of 39 Intermediate
- Control nodeUbuntu 26.04 LTS
- Python3.14.4
- requests2.34.2
- paramiko5.0.0
- TimeAbout 20 min
requests reads ~/.netrc automatically, which surprises people; it has done so for a long time and is not new. The netrc module rejects a world-readable file on Unix.
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
This guide includes
Use this when the request needs a token. This matters because getting the token into the header is one line - and there are four ways it then leaks into a log, one of them written by the library rather than by you.
- reading the 401 before you authenticate
- sending the header, with the token kept out of the source
- building a Session that carries the credential
- meeting the four ways a token leaks, and writing a redaction filter that actually works
- keeping a token in a file with the permissions that implies, plus
~/.netrcand basic auth
Before you start
- guide 7 - where the token comes from.
- guide 20 -
os.openwith a mode, used here. - guide 6 - the handler this filter attaches to.
-
The 401, and what it tells you
-
The header, and the token that must not be in the source
-
A Session that carries the credential
-
The four ways a token leaks
-
A redaction filter, and why the obvious one breaks
-
So redact the formatted message instead
-
And the library that logs the URL for you
-
A token in a file, with the permissions that implies
-
The file the other tools already agree on
-
Basic auth, and what it actually sends