Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel CSRF Token

Tags:

csrf

laravel

EDIT: I should have said this at the start, I'm using AngularJS in the FronEnd, and I'm making all the request via XHR. I'm developing an Application using CSRF Token for every user request.

Should I regenerate the Token after each request?

Something like

Session::forget("_token") and Session::put("_token", RANDOM_SOMETHING)

Or is it enough to use the same one each user Session?

Is there any benefit?

like image 692
Gabriel Matusevich Avatar asked Apr 05 '14 05:04

Gabriel Matusevich


4 Answers

With Laravel 5 using Blades templates, it's pretty easy.

If you only want the value of the csrf token, you can generate it by writing:

{{ csrf_token() }}

which generates the token value like this:

7YC0Sxth7AYe4RFSjzaPf2ygLCecJhPbyXhz6vvF

If you are using forms, you can add the following line of code inside the form:

{{ csrf_field() }}

which will generate html like this:

<input type="hidden" name="_token" value="7YC0Sxth7AYe4RFSjzaPf2ygLCecJhblahblah">
like image 162
madarasz Avatar answered Oct 08 '22 22:10

madarasz


Laravel should be doing this for you, you don't need to manage the creation / deletion of _token

<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

See the 'CSRF Protection' section in the docs here: http://laravel.com/docs/security

like image 45
duellsy Avatar answered Oct 08 '22 23:10

duellsy


If you are using Laravel 5.6, do the following at the top of forms to create hidden input field for the CSRF token

  @csrf
like image 9
Joyal Avatar answered Oct 08 '22 22:10

Joyal


Depends. If the attacker is not MITM, in the sense that they cannot eavesdrop on traffic between your web app and the API server, a single CSRF token for the entire session should be enough.

Assuming you guard sensitive operations on the server-side too (i.e. allow access to resources only to the owner of the resource, e.g. "delete my account", etc.) the token would ensure that the browser making the request is the legitimate, authenticated user's browser. That's all you should worry about, I think.

On the other hand, if the attacker is capable of looking at non-secure traffic between the web app and your API, they may get hold of the CSRF token and your session_id and do evil stuff transparently. In such case granting, using and subsequently discarding a token for each request (POST, or any kind that does sensitive operation) only makes their job a bit more difficult, but you're still doomed.

My 2 cents...

like image 7
hlev Avatar answered Oct 08 '22 23:10

hlev