T
T
TCloud2020-12-24 17:22:08
PHP
TCloud, 2020-12-24 17:22:08

Why does the token break when authorizing via curl?

Hello!
There is a problem with authorization on the site through a script (php curl). The problem is that when sending a POST request for authorization, the csrf token "breaks", which causes a redirect back to the authorization page and the "Invalid CSRF token" error is displayed in the form.

The parsing flow is as follows:
1. GET request to get the html authorization page + opening a session and writing cookies;
2. Parsing CSRF token via PhpQuery;
3. Sending a POST request with authorization data + a token in the form "application/x-www-form-urlencoded" + writing and reading cookies;

at the 3rd step, an error actually occurs, I can’t figure it out, maybe someone knows? code below.

1. GET request and token parsing

// GET CSRF TOKEN
$connectionStream = curl_init();

curl_setopt_array($connectionStream, [
    CURLOPT_URL => $LOGIN_PAGE_URL,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_HEADER => 0,
    CURLOPT_COOKIESESSION => true,
    CURLOPT_COOKIEJAR => $COOKIE_FILE,
]);

$response = curl_exec($connectionStream);
$responseCode = curl_getinfo($connectionStream, CURLINFO_HTTP_CODE);

if($responseCode === 200)
{
    $phpQuery->load_str($response);
    $nodesCollection = $phpQuery->query('[name="_csrf_token"]');
    $token = $nodesCollection[0]->getAttribute('value');
}


2. POST request for authorization
// LOGIN
$postFields = implode('&', [
    '_csrf_token=' . $token,
    '_username=' . $LOGIN_NAME,
    '_password=' . $LOGIN_PASS,
    '_submit=',
]);

curl_setopt_array($connectionStream, [
    CURLOPT_URL => $LOGIN_REQUEST_URL,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => $postFields,
    CURLOPT_RETURNTRANSFER => false,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_COOKIESESSION => true,
    CURLOPT_COOKIEJAR => $COOKIE_FILE,
    CURLOPT_COOKIEFILE => $COOKIE_FILE,
    CURLOPT_HEADER => 0,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/x-www-form-urlencoded',
        'Upgrade-Insecure-Requests: 1',
    ]
]);

$response = curl_exec($connectionStream);
$responseCode = curl_getinfo($connectionStream, CURLINFO_HTTP_CODE);

if($responseCode === 200)
{
    var_dump($response);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nokimaro, 2020-12-24
@nokimaro

Judging by the description, you are doing everything according to your mind
. You just need to find an error in the code. In a nutshell:
1. Make sure that $postFields is not an empty token
2. Check the cookies being sent
3. Some http header may be missing, for example, the receiving side also checks the Referrer or does not accept requests with suspicious user-agents of the Curl type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question