brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: curl --oauth2-bearer sends a Bearer token without typing the header

Curl
~/tips/tip-curl-oauth2-bearer-token

curl --oauth2-bearer "$TOKEN" https://api.example.com/v1/items

Pass an API token with --oauth2-bearer and curl builds the Authorization: Bearer header for you.

Most token-based APIs want an Authorization: Bearer ... header, and typing that header by hand is easy to get slightly wrong. curl has an option that takes only the token.

curl --oauth2-bearer "$TOKEN" https://api.example.com/v1/items

The manual describes --oauth2-bearer as the way to give the bearer token for OAuth 2.0 server authentication, formatted according to RFC 6750. It is listed for IMAP, LDAP, POP3, SMTP and HTTP.

To see what goes over the wire, add -v. Against a local test server on curl 8.5.0, this line appeared in the request:

> Authorization: Bearer mF_9.B5f-4.1JqM

That is the same as -H "Authorization: Bearer $TOKEN", minus the typing. It combines with other options, for example --json to post a body:

curl --oauth2-bearer "$TOKEN" --json '{"name":"widget"}' http://localhost:8000/items

The manual adds that if you pass the option several times, the last value wins. That helps in a script where a default token sits in a variable and one call needs another.

The caveat is the token itself. Keep it in an environment variable instead of typing it in the command, so it doesn’t land in your shell history. Remember that -v output prints the token in clear text, so scrub it before you paste logs into a bug report.

Further reading: curl manual: –oauth2-bearer

More Curl tips curl -si -X POST -H 'Content-Type: application/json' \ – trigger: webhook curl --trace-ascii – https://example.com/ Retry-After: 120 curl -fsS --fail-early \ All Curl tips (74) All topics

Link