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.

CloudwaysCDN — a powerful solution that offers superior performance and satisfied global audience for your business. Read More

How to Use Laravel CSRF Protection for Your Apps

Updated on  10th August

6 Min Read
laravel csrf
Reading Time: 6 minutes

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.

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.

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.

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.

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.

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:

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:

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

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 pardeep.kumar@cloudways.com

Create Laravel apps without the worry of server management.

Deploy your app on optimized PHP hosting servers for Laravel.

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

THERE’S MORE TO READ.