A very important part of an online application is the security, and Laravel make protecting your website from CSRF attacks nice and easy.
To avoid forgetting to add the CSRF protection to each and every route requested via the HTTP POST method, we can attach the CSRF filter in a much more intuitive way – using the Route::when()
method.
Add CSRF protection to all POST requests
Open up app/routes.php
and add the following:
Route::when( '*', 'csrf', array( 'post' ) );
Yes. That’s all you need to do on the server side.
If you want to see what’s going on behind the scenes, open up app/filters.php
and look for the csrf
filter. It should look something like this:
/* |-------------------------------------------------------------------------- | CSRF Protection Filter |-------------------------------------------------------------------------- | | The CSRF filter is responsible for protecting your application against | cross-site request forgery attacks. If this special token in a user | session does not match the one given in this request, we'll bail. | */ Route::filter('csrf', function() { if (Session::token() != Input::get('_token')) { throw new Illuminate\Session\TokenMismatchException; } });
As you can see above, it’s checking for an input parameter of _token. Which brings us nicely into the next section…
Add the CSRF token to your POST method forms
If you use the Laravel form builder, I believe it’ll generate the CSRF token automatically for you. Otherwise it’s simple enough to add it yourself. Just place the following inside a form, or pass it through to a blade template (you may need to use echo
if you’re adding this PHP directly into the page):
Form::token()
You’re now protected from some more nasties lurking out there, without even breaking a sweat!