jeffery_the_wind jeffery_the_wind - 9 months ago 36
Java Question

Session dying when using curl from command line

I mad a simple java web app using sparkjava. It fields GET and POST requests. I made my own simple authentication script, which authenticates the user using the secret password and stores the username in the session:

Make sure authenticated
before((req, res) -> {
boolean authenticated = false;
if ( req.session().attribute("user") != "casumo_user" ) {
if (req.queryParams("secret").equals(System.getenv().get("SECRET"))){
authenticated = true;
}catch (Exception e){
halt(401, "{\"error\":\"Please Authenticate.\"}");
authenticated = true;

if (!authenticated) {
halt(401, "{\"error\":\"Please Authenticate.\"}");

I was using the Postman Add-on for Chrome, and this was working fine. I would authenticate once, and the server would keep my session alive for subsequent requests.

The problem is I wanted to use curl to make the same requests, but the session was not staying alive from one request to another.

For example, first I use this command:

curl -s -L --data "secret=secret_password" url/auth | jsonpp

{ "msg": "Authenticated! You can now make requests." }

But then making a sebsequent GET request proves that the session is not preserved/

curl -s -L url/films | jsonpp

{ "error": "Please Authenticate." }

Using the Postman App would allow me to make GET and POST requests for quite some time after authenticating 1 time. Is it possible to do this using curl from the command line like I have here? Or is my authentication system not robust enough to use curl from the command line?


The project is on GitHub.


If you want curl to store cookies between calls, you need to tell it to do so.

Check out the --cookie and --cookie-jar options.

curl --cookie-jar cookies.txt -s -L --data "secret=secret_password"
# then
curl --cookie cookies.txt --cookie-jar cookies.txt -s -L url/films

The --cookie-jar option tells curl to write any cookies it received to the file when the request ends, and the --cookie option instructs it to read cookies from that file for issuing requests.

That should allow you to log in, and then use the cookies to re-establish the session on subsequent requests.

curl --help and man curl are your friends!