Testing web apps and older APIs often means logging in once and reusing a session cookie.
curl ignores cookies unless you tell it otherwise. Two options cover almost everything:
-c jar.txt(cookie jar) writes all cookies curl knows at the end of the run to a file.-b jar.txtreads cookies from that file and sends the matching ones.-bwith a string containing=sends that literal cookie instead:-b 'session=abc123'.
Using both on the same file, -b jar.txt -c jar.txt, lets a series of commands behave like a browser session: the login response sets a session cookie, later requests send it, and updated cookies are saved back.
A typical scripted login:
- POST the credentials (and any CSRF token you scraped) with
-c jar.txt. - Call protected pages with
-b jar.txt.
The jar uses the Netscape cookie file format, a tab-separated text file, so you can inspect it. Expired cookies are dropped, and session cookies (no expiry) are kept only because you explicitly save them. Passing -b '' (empty string) enables the cookie engine without loading anything, which matters when you follow redirects with -L that set and then require a cookie.
Treat jar files like passwords: a session cookie is as good as being logged in. Delete them when done.
Example
# 1. log in and save the session cookie
curl -sS -c jar.txt -d 'user=ann&password=hunter2' https://app.example.com/login
# 2. reuse it for authenticated requests
curl -sS -b jar.txt https://app.example.com/api/me
# {"user":"ann"}
# keep the jar updated across calls
curl -sS -b jar.txt -c jar.txt https://app.example.com/dashboard -o /dev/null
# send a literal cookie instead of a file
curl -sS -b 'session=abc123; theme=dark' https://app.example.com/api/me
grep -v '^#' jar.txt # Netscape format: domain, path, secure, expiry, name, value
rm jar.txtRemember
- -c file saves cookies, -b file sends them
- -b 'name=value' sends a literal cookie string
- Use -b and -c on the same jar to mimic a browser session
Watch out for
- Using -c only and expecting the next command to be logged in; reading requires -b.