How to pass a CSRF token with an Ajax request in Laravel?


CSRF stands for Cross-Site Request Forgeries. CSRF is a malicious activity performed by unauthorized users acting to be authorized.

Laravel protects such malicious activity by generating a csrf token for each active user session. The token is stored in the user's session. It is always regenerated if the session changes, hence the token is verified for each session to make sure the authorized user is performing any task. Here is an example to get access to the csrf_token.

To generate csrf token

You can get the token in two ways.

  • By using the $requestsession()token()

  • By using the csrf_token() method directly

Example

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller { public function index(Request $request) { echo $token = $request->session()->token(); echo "<br/>"; echo $token = csrf_token(); } }

Output

The output for above is −

13K625e8mnDna1oxm9rqjfAPfugtTlYdndBoNR4d
13K625e8mnDna1oxm9rqjfAPfugtTlYdndBoNR4d

CSRF token in blade template

Whenever you have to make use of POST, PUT, PATCH, DELETE in your html form make sure to have the csrf token as hidden field in your html form. This will make sure that the request made is protected using CSRF middleware protection.

Inside blade template you can make use of @csrf directive that will help you generate the csrf token that can be later stored as hidden field as shown below −

Example

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller { public function index(Request $request) { return view('hello'); } }

hello.blade.php

<form method="POST" action="/student"> @csrf <!-- Equivalent to... --> <input type="hidden" name="_token" value="{{ csrf_token() }}" /> </form>


Using csrf token inside Ajax request

Here will make use of Ajax requests and also pass the csrf token in it. To work with csrf token inside Ajax. You need to add the csrf token in head section of html as shown below −

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

Include a jquery file in your html as we are going to make use of $.ajaxSetup() and $.ajax to make ajax call.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Later call ajaxsetup with headers as shown below −

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

Now make an ajax call as shown below −

$.ajax({ type:'POST', url:'/getdata', success:function(data) { $("#data").html(data.msg); }, error: function (msg) { console.log(msg); var errors = msg.responseJSON; } });

The complete code in ajaxtest.blade.php is −

<html> <head> <title>Ajax CSRF TOKEN Example</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> function getData() { console.log("ABCD"); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type:'POST', url:'/getdata', success:function(data) { $("#data").html(data.msg); }, error: function (msg) { console.log(msg); var errors = msg.responseJSON; } }); } </script> </head> <body> <div id = 'data'></div> <?php echo Form::open(array('url'=>'/ajaxtest'));?> <?php echo Form::button('Click Me',['onClick'=>'getData()']);?> <?php echo Form::close(); ?> </body> </html>

AjaxCSRFController.php

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class AjaxCSRFController extends Controller { public function index() { $data = "Hello World"; return response()->json(array('msg'=> $data), 200); } }

Inside routes/web.php create the routes for CSRF testing

Route::get('ajaxtest',function() { return view('ajaxtest'); }); Route::post('/getdata',[AjaxCSRFController::class, 'index']);

Now hit the url : http://localhost:8000/ajaxtest in browser and you will get following output −

Now click on the button Click Me and see the message getting displayed.

Updated on: 30-Aug-2022

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements