DerickMasai
DerickMasai

Reputation: 111

How to solve Laravel not generating CSRF token

Okay, so I've been using jQuery to connect to a controller function that authenticates data and submits it via AJAX using this code. This was working flawlessly until I took a day off on Saturday. Coming back to the project yesterday I keep encountering this error with HTTP code 419

"message": "CSRF token mismatch.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
"file": "C:\\workspace\\app_name\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
"line": 387,

So I tried to echo the CSRF token and it's blank! Keep in mind it was working perfectly Friday then come Sunday (yesterday), with no external input, it just randomly hits me with this. What could be the reason for it not generating a token?

Upvotes: 2

Views: 5160

Answers (2)

DerickMasai
DerickMasai

Reputation: 111

Okay, so I simply added this code quickly to my code just before the workday ended so didn't have time to test hence failed to notice the error.

$request->session()->flush();

This line of code is responsible for clearing sessions. What it DOESN'T mention in the Laravel docs though is that since CSRF tokens are sessions AS WELL, using this basically makes IO to your databases impossible since it clears ALL sessions including said tokens. So until this is resolved (ideally with a code snippet that clears dev-created sessions while sparing inbuilt Laravel ones), avoid using this line of code. Instead, use this to clear single sessions:

// Forget a single key...
$request->session()->forget('name');

Or this to clear multiple sessions

// Forget multiple keys...
$request->session()->forget(['name', 'status']);

You can also learn more about this beautiful framework's sessions here.

Lastly, thank you to @Indra Kumar S, @John Lobo, @Manjeet and @Paras Raiyani for taking the time to browse the platform and to offer assistance to others. Will definitely be doing the same.

Upvotes: 2

mk23
mk23

Reputation: 1403

Run below commands :

php artisan key:generate

and then clear cache

php artisan cache:clear 

If you want to see if the token value is changing then try below code

Route::get('/token', function (Request $request) {
    $token = $request->session()->token();
    echo $token;
    $token = csrf_token();
    echo $token;

});

Upvotes: 1

Related Questions