Laravel CSRF protection Laravel CSRF protection laravel laravel

Laravel CSRF protection


  1. Where does it create the token (what part of the code triggers it)?

After going through the helpers file

/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php

which had the definition of csrf_token() helper method, which calls the token method on

/vendor/laravel/framework/src/Illuminate/Session/Store.php

and if you check the start() which calls regenerateToken() if _token hasn't been set, it save a random 40 character string to the session with the key of _token

/** * Regenerate the CSRF token value. * * @return void */public function regenerateToken(){    $this->put('_token', Str::random(40));}
  1. Where is the token stored after creation, in cookie? In session? How can I extract and see what has been stored? Is this all actually controlled by session.php?

The token is stored in session, you can extract it using session('_token'). The session expiration time is controlled in session.php using

'lifetime' => env('SESSION_LIFETIME', 120),'expire_on_close' => false,
  1. What does this mean when I reload the page, is the token still the same as the session.php has 120 min default lifetime?

If you check start() in /vendor/laravel/framework/src/Illuminate/Session/Store.php

/** * Start the session, reading the data from a handler. * * @return bool */public function start(){    $this->loadSession();    if (! $this->has('_token')) {        $this->regenerateToken();    }    return $this->started = true;}

the token is regenerated if the session does not have _token. So _token would be same until the session expires


In my case removing APP_URL=http://localhost from .env solved problems with CSRF token. I do not configure fixed value in APP_URL for local dev because I use always different hostnames via browser and sometimes ports.