user3693952
user3693952

Reputation: 11

Auth lost when doing a curl request to my laravel server

I'm trying to make a curl request to my laravel server, in that request I have to check whether the user of my laravel application is logged in or not. I use this code:

$transferAmount = 200;
    //set POST variables
    $url = URL::route('post-spend-partner');

    $fields = array(
        'transferAmount' => urlencode($transferAmount),
        'cancelUrl' => urlencode(URL::route('get-return-page-example')),
        'returnUrl' => urlencode(URL::route('get-return-page-example')),
    );


    // New Connection
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_exec($ch);
    curl_close($ch);

In the requested url I'm just checking if I'm logged in or not, but it always returns false:

public function postSpendPartner() {
    echo "Authenticated? " . (Auth::check() ? 'Yes' : 'No');
}

I know for sure that I'm logged in, if I try the exact same thing with Ajax it completely works!

Does anyone know what I could try, to solve this problem?

Best regards!

Fabrice

Upvotes: 1

Views: 1715

Answers (2)

jithujose
jithujose

Reputation: 551

Try sending your cookies as a header with your curl request.

// ...
$cookie_header = "Cookie:";
$headers = [];

foreach($_COOKIE as $key => $val) {
    // Do sanitize cookie values
    $cookie_header .= " ".$key."=".$value.";";
}

$headers[] = $cookie_header;

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// ...

You could filter out unnecessary cookie values from $cookie_header.

Upvotes: 0

Bramus
Bramus

Reputation: 2059

Some facts: HTTP is stateless. Session IDs need to be passed to the server in order to continue the session. Session IDs are (most of the time) stored in cookies. Cookies are included in the request.

Using a cookiejar could indeed be one possible solution. The fact that it works using Ajax, and not by re-submitting the request from your server might be because of the session-verification mechanism on the server: Some session implementations lock session IDs to the initial IP address. If the contents of your cookiejar file check out, that might be the culprit.

That aside: re-submitting the request via Curl from your server is a severe codesmell to me. A proper solution would to implement something such as OAuth.

Upvotes: 1

Related Questions