This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

How to Use Laravel CSRF Protection for Your Apps

Updated on December 10, 2021

6 Min Read
laravel csrf

Cross Site Request Forgery also known as CSRF is a type of attack in which a malicious website, email, message or any other program causes users to perform unwanted actions on websites that they are visiting at the instant.

Popular PHP frameworks like Laravel have in-built function, called Laravel CSRF protection, which makes the applications highly secured against this attack.

The limitation of any CSRF attack depends upon the vulnerabilities exposed by the application, as it only targets those weaknesses of the application which are prone to the attack. For example, business oriented login applications are highly vulnerable to the CSRF attack, which are used in various  transactional activities.

The CSRF attack can affect your account, changing login credentials, that you use on any ecommerce platform to buy products.

Laravel CSRF
1. Impacts of CSRF Attack
2. Laravel CSRF Token Protection
3. Prerequisites
4. Laravel CSRF in Forms
5. Handling Laravel CSRF when Using Axios
6. Laravel CSRF Token Ajax Calls

7. Excluding URIs From CSRF Protection
8. FAQs
9. To Wrap Things Up!

Therefore, with this CSRF breach, attackers target specific vulnerabilities of the application to perform any detrimental function without the knowledge of end-user.

Any malicious program or web content can disrupt your routine web operations through using user’s session with the website, and hence compromises sensitive information through it.

Related: Comprehensive Laravel Security Guide

Impacts of CSRF Attack

Impacts of CSRF attacks vary with the privileges of victim it is targeting at. For example, if a normal user has been targeted by the CSRF attack, then it could hamper his / her personal data and associated functions.

Meanwhile if the attack is meant for any administrator account, then it could comprise the security of entire application.

Social networking websites are the most likely  target for a CSRF attack, as intruders try to compromise confidential data of users through these websites.

Meanwhile, the business-oriented websites that users use to carry out transactional operations including (banks, stock brokerages, bill paying services) are also highly prone to the CSRF attack.

Any deliberate CSRF attacker can embed malicious HTML or Javascript code into an email, website, browser popup or in any other entity to perform secretive unwanted operations.

It is a matter of fact that the end-user remains totally unaware of these malicious activities and disruptive tasks executes with or without the user’s permission either directly or by utilizing CSRF scripting mechanism (ex: Samy MySpace Worm).

Laravel CSRF Token Protection

Today, many PHP frameworks like Laravel and others have built-in support for protecting web apps against Cross Site Request Rorgery (CSRF) attacks.

The CSRF function of Laravel automatically generates Laravel CSRF token for each active user session. This token helps to verify that the request and approval for application is only given to the authenticated user.

However despite all these built-in functionalities available, many developers are still not clear how to use this CSRF protection tool in their Laravel applications.

Therefore in this article, I will demonstrate you how to protect your applications using the Laravel CSRF. As for the demonstration purpose, I have used Laravel employee management system to show the concept and usage of CSRF protection.

Prerequisites

For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • PHP 7.1
  • MySQL

I have used Laravel application on a Cloudways managed Laravel server because it gives a highly optimized hosting stack and takes care of any server level issue. You can signup for a free account on Cloudways.

You might also like: Enhanced Cloudways Staging Environment Is Now Available for All Users

Laravel CSRF in Forms

Defining your form fields in view, you should always include hidden CSRF token form fields to ensure that the CSRF protection middleware can validate the request by it. Hence by using @csrf in the form fields, Blade directory generates the secured fields to validate the process.

<form method="POST" action="/employee">

   @csrf

   ...

</form>

So the VerifyCsrfToken in the Laravel will automatically verify that the token which has requested input either matches the token stored in session or not, and hence will allow the access to the resource after token verification.

You might also like: Ultimate PHP Security Best Practices Guide

Handling Laravel CSRF when Using Axios

You don’t have to worry about adding any CSRF token to your request if you are using Axios client for sending HTTP requests. Because it is the default functionality of Laravel that it automatically attaches CSRF token to the requests when it is sent using Axios. The Axios client settings is found inside the file resources/assets/js/bootstrap.js.

For sending request with any client other than Axios, you will need to attach CSRF token manually, which depends upon how you use JavaScript in your application.

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;

} else {

   console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');

}

Laravel CSRF Token Ajax Calls

In Laravel, Middleware handles all the requests and doesn’t allow any POST request without the right CSRF token verification. Therefore, in order to proceed further, you must input the CSRF Token while sending the AJAX request.

data: {  

          "_token": "{!! csrf_token() !!}"

       }

$.ajax({

  type: "POST",

  data: {"_token": "{{ csrf_token() }}","id": id},

  url: some_url,

  success: function(msg){

    // response

  }

});

Ajax Headers

It places the CSRF token generated by Laravel and adds it to the headers of the site’s Ajax requests using jQuery’s ajaxSetup method.

$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });

Laravel CSRF Custom Header Posts

First create a global variable in Javascript that will hold the current value of _token, you can add this code to your html header. Then afterwards put that _token to each ajax request.

<script> var _token = '<?php echo csrf_token(); ?>'; </script>

CSRF Filter

Change the existing File Filter with the name, filter.php, which is found in the root of the app folder. Inside the file, there is an existing CSRF protection filter that ships with Laravel. Modify the filter as mentioned below:

Route::filter('csrf', function()

{

   if (Request::ajax())

   {

       if (Session::token() !== Request::header('csrftoken'))

       {

           // Change this to return something your JavaScript can read...

           throw new Illuminate\Session\TokenMismatchException;

       }

   }

   elseif (Session::token() !== Input::get('_token'))

   {

       throw new Illuminate\Session\TokenMismatchException;

   }

});

The main function of this filter is to check whether the passed request is of Ajax or not, if found true then validates the token passed in the headers. If the request doesn’t match the one stored in Laravel’s session, then throws an error exception.

You might also like: Using Redis As a PHP Session Handler

Excluding URIs From CSRF Protection

At some points, you might wish to exclude certain URLs from CSRF protection. For instance, if you are using Stripe and its webhook system for processing payments, then you will need to omit your Stripe webhook handler route from CSRF protection, because Stripe will not have the knowledge about your routes initially, where the CSRF tokens would be sent.

Therefore these routes should be placed outside of the web middleware group and the RouteServiceProvider should get apply to all routes in the routes/web.php file.

While besides this, you can also exclude particular routes from the VerifyCsrfToken middleware, by adding their respective URLs to the $except property:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware

{

   /**

    * The URIs that should be excluded from CSRF verification.

    *

    * @var array

    */

   protected $except = [

       'stripe/*',

       'http://example.com/foo/bar',

       'http://example.com/foo/*',

   ];

}

FAQs

Q1: What Is Laravel CSRF Token?

A: To help protect the data privacy against the Cross Site Request Forgery (CSRF) attacks, Laravel has introduced a user verification token named Laravel CSRF Token, with a sole purpose to verify and validate the users sessions. It ensures that the request and approval for any particular resource / program is only given to the authenticated users who have verified tokens. As if that Laravel CSRF token mismatches with the one stored in Laravel’s session, then it quickly denies access to the resource requested by particular token.

Q2: How Laravel Csrf Token Works?

A: Laravel generates a particular CSRF Token for each user session, which means real users can only access the required information by validating with the CSRF Token. Every token is first checked and validated from the Laravel’s session, before giving access to any program or resource. If that Laravel CSRF token is not found in the stored session, then is denied access to the resource.

Q3: Why is it common to put CSRF prevention tokens in cookies?

A: It is a common practise to put CSRF prevention token in cookies because once it is placed there, makes it available for usage for the application, both in regular form and AJAX Posts. Particularly, it prevents attackers to use their own set of generated CSRF tokens, as the fixation of real CSRF tokens in cookies helps validating-out the forged tokens.

Q4: How to Disable CSRF Laravel?

A: You can disable CSRF Laravel from the App/Http/Kernel.php file by removing  App\Http\Middleware\VerifyCsrfToken from the $middleware array.

Q5: Why refresh CSRF token per form request?

A: Generating a new CSRF token for each request is not necessary. However, it is only important for login purposes, because it provides an authentication check for each login attempts. The purpose of having a Refreshed Laravel CSRF token is that it prevents session fixation from any deliberate web attacker, and as a result possibility of any intended CSRF attack. Besides it, there isn’t any particular need to generate a new CSRF token for every request.  

 

To Wrap Things Up!

This brings us to the end of this blog. It highlights the details about Cross Site Request Forgery (CSRF) attack and how you can guard your Laravel application against it by using the effective security mechanism of Laravel CSRF.

The smart verification process of the user session through specified tokens makes security of Laravel applications much better, giving the edge over intended CSRF attacks.

I have demonstrated in detail how you could use CSRF tokens to make sure your Laravel application remains safe from the unwanted forged attacks and its security check always stays on high.

Still if you have got any other question(s) regarding Laravel CSRF and its implementation in the application, feel free to ask in the comments section below. I will answer them accordingly.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Pardeep Kumar

Pardeep is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He love to work on Open source platform , Frameworks and working on new ideas. You can email him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now