Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - CSRF token never changes

I am creating forms, and it does not matter how I do it, the CSRF _token is always the same!

It doesnt matter if I use

{{ Form::open([route' => 'login']) ]]

or if I use

{{ Form::token() }}

It is the same one every single time. Even after I make a successful Form submission. I figured it would get consumed and a new one would be generated, but no!

Did I miss a configuration step?

Note: I know that if the laravel_session gets regenerated, the _token is different, but as I had understand, the CRSF token was also the mechanism to avoid multiple form submissions , so it should change on every refresh of page, or at least after is consumed after one successful post submission, no?

like image 204
Enrique Moreno Tent Avatar asked Jul 19 '14 17:07

Enrique Moreno Tent


People also ask

How long does CSRF token last Laravel?

It becomes invalid once your session expires. Thus if you set the lifetime to 1 week, CSRF token will only expire after 1 week. This can achieved like this in config/session.

How does CSRF token works Laravel?

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the person actually making the requests to the application.

Is CSRF token unique per request?

A CSRF Token is a secret, unique and unpredictable value a server-side application generates in order to protect CSRF vulnerable resources. The tokens are generated and submitted by the server-side application in a subsequent HTTP request made by the client.


2 Answers

It is not necessary to refresh the CSRF token for every request, generating the token per session will also be safe. Have a look at the Owasp cheat sheet for a better explanation.

Regenerating the token for every request can be done, but can result in usability issues. I think this is the reason why Laravel implements the token per session approach.

like image 125
martinstoeckli Avatar answered Sep 21 '22 22:09

martinstoeckli


From the code, the only relevant occurrences of _token or regenerateToken are in the Illuminate/Session/Store, lines 89, 551 and 571. The occurences being:

public function start()
{
    $this->loadSession();

    if ( ! $this->has('_token')) $this->regenerateToken();

    return $this->started = true;
}

public function token()
{
    return $this->get('_token');
}

public function regenerateToken()
{
    $this->put('_token', str_random(40));
}

This means, that token gets only regenerated, when not present in Sessions. You have to regenerate it yourself if you want, with i.e. Session::forget('_token');

like image 26
peter.babic Avatar answered Sep 19 '22 22:09

peter.babic