What Is The Use Of CSRF Protection In Laravel Framework

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

Cross-Site Request Forgery (CSRF) is a type of attack that performed by the attacker to send requests to a system with the help of an authorized user who is trusted by the system. Laravel provides protection with the CSRF attacks by generating a CSRF token. This CSRF token is generated automatically for each user. This token is nothing but a random string that is managed by the Laravel application to verify the user requests. CSRF token protection can be applied to any HTML form in Laravel application by specifying a hidden form field of CSRF token. The requests are validated automatically by the CSRF VerifyCsrfToken middleware.

What Is The Use Of CSRF Protection In Laravel Framework

Define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the @csrf Blade directive to generate the token field:

we can create in three different way

 


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



<form method="POST"<

  // Generate hidden input field
  {{ csrf_field() }}  
  .....
  .....
</form>



<form method="POST">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
  .....
  .....
</form>
 

CSRF Tokens & JavaScript

When building JavaScript driven applications, it is convenient to have your JavaScript HTTP library automatically attach the CSRF token to every outgoing request. By default, the Axios HTTP library provided in the resources/js/bootstrap.js file automatically sends an X-XSRF-TOKEN header using the value of the encrypted XSRF-TOKEN cookie. If you are not using this library, you will need to manually configure this behavior for your application.
 

Excluding URIs From CSRF Protection

Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.

Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:

 
<?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/*',
    ];
}
 

X-CSRF-TOKEN

In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in an HTML meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">


Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

$.ajaxSetup({
    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 that is included with each response generated by the framework. You can use the cookie 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 header on same-origin requests.

Example(1)

1.Create new laravel project and open and Create route in web.php

composer create-project --prefer-dist laravel/laravel laraveldemoproject


web.php
 
Route::get('form', 'demoController@form');


2.Create demoController and implement below code

Use a below command to create demo controller

php artisan make:controller demoController


app\Http\demoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class demoController extends Controller
{
      public function form(){

       return view('form');
    }
}


3.Create and open form.blade.php file in resource\view folder and implement code as below

<!DOCTYPE html>
<html>
<head>
    <title>CSRF Protection In Laravel</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>CSRF Protection</h1>
    </div>
    <h2></h2>
    <div class="form-group col-sm-2"></div>
    <div class="form-group col-sm-8">
        <div class="well">
            <form method="post" action="">
                    @csrf
                <div class="form-group col-sm-12">
                    <label>Name</label>
                    <input  class="form-control" type="text" name="Name" value="">
                </div>
                <div class="form-group col-sm-12">
                    <label>Description</label>
                    <input  class="form-control" type="text" name="Description" value="">
                </div>
                <div class="form-group text-center">
                    <input  class="btn btn-primary" type="submit" >
                </div>
            </form>
            <div class="form-group col-sm-2"></div>
        </div>
    </div>
    <br>
</div>
</body>
</html>


4.Now to store data create url in form that will cal the formsote route 

<form method="post" action="{{url('formstore')}}">


5.Now again open web.php and implement code as below

Route::post('formstore', 'demoController@formstore');


6.After formstore route called it will redirect to demoController in that it will reach formstore

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){

        return $request->all();
    }
}


7.when you submit form all data will return from formstore function

8.use below code to run url in google chrome

http://localhost/laraveldemoproject/public/formstore


9.you get below output

{"_token":"1J1BCwqseCMM76E7HO8BrdA9topVxB8SlO4hxl93","Name":"name","Description":"desc"}

Related Post