What is the CSRF token in laravel and interesting tricks?

What Is the CSRF Token in Laravel and Interesting Tricks?

Hi guys,

Today we are studying What is the CSRF Token in Laravel So, Don’t skip this article You get the best knowledge. Stay connected!

Using Laravel, it is easy to protect your application from cross-site request forgery attacks. It is a malicious exploit where unauthorized commands are performed against authenticated users. Laravel auto-generates a CSRF token for each active user session managed by the application. The Laravel verifies the authenticated user token is the one making the requests to the application.

You can add a CSRF token field in the form. It validated on CSRF protection middleware. You add the @csrf blade directive to generate the token fields.

<form method="POST" action="/profile">
    @csrf
    ...
</form>

The VerifyCsrfToken Middleware will automatically verify that the token in the request input matches the token stored in the session.

CSRF Token & Javascript

Assume you are making a JavaScript-driven application. You need to send an X-XSRF-TOKEN header using the value of the encrypted XSRF-TOKEN cookie to every outgoing request.

Excluding URI from CSRF protection

Sometimes, you need to exclude a set of URIs from CSRF protection. Such as if you integrate a payment gateway. Some payment gateway calls back the URL with transaction data and POST HTTP method. In that case, it must pass the callback URL to $except the property of the VerifyCsrfToken Middleware.
While testing, CSRF middleware is auto-disabled. The VerifyCsrfToken Middleware file looks like the below:

<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should exclude from CSRF verification.
*
* @var array
/ protected $except = [ 'stripe/',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
}

X-CSRF-TOKEN

The VerifyCsrfToken Middleware will also check for the X-CSRF-TOKEN request header. Such as an added HTML meta tag for storing tokens. Also, you can add a CSRF token to Ajax calls for CSRF protection.

$.ajax({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})

X-XSRF-TOKEN

Laravel stores the current CSRF token in an encrypted XSRF-TOKEN cookie. It includes each response generated by the framework. You can use the token value to set the X-XSRF-TOKEN request header.

This cookie is primarily sent as a convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN the header on same-origin requests.

Thank you for reading this article and share this article with your friend circle. Stay Connected, Stay Blessed!

Cheers,

Loading

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top