Updated May 25, 2023
Introduction to CSRF Token Laravel
The following article provides an outline for CSRF Token Laravel. The worldwide web, even though a beautiful place to be, is also filled with malicious users. They use technology and trust to attack systems to gain entry and access. Once they have entered the system, all hell may break loose. Identities may be stolen, and financial and personal details may be stolen. Armed with this information, the attacker may cause irreparable damage. Most malicious attacks are harmless to look us. These may come in the form of spam or phishing sites. The user will have no clue to differentiate between a simple site asking for donations about education for poor kids or a place created mainly to gain illegal access to someone’s credit card or banking information. This kind of attack is termed a CSRF or Cross-Site Forgery attack.
These vicious attacks can debilitate and must be handled with utmost safeguards. The Laravel Framework is one of the most sought-after frameworks for a few reasons. It is a robust and scalable framework that allows users to create functionalities that can withstand the rigors of modern-day consumer usage. The Laravel Framework also has an expressive query command line system, which enables the programmer to build services quickly and effortlessly. Because Laravel is an open framework, third-party programs and frameworks can be integrated into its systems. This is also one of the reasons why ecommerce designers and owners prefer the Laravel Framework. The Laravel Framework is also mindful of the attacks that occur in the digital world. Hence it has created mechanisms to protect the user from falling prey.
Let us have a look at the kind of mechanism that the Laravel framework has created to stop CSRF attacks:
Code:
<form method = "POST" action="/profile">
{{ csrf_field() }}
...
</form>
A form with the standard CSRF token will look like:
<form>
<label> Email </label>
<input type = "text" name = "email"/>
<br/>
<label> Message </label> <input type="text" name = "message"/>
<input type = "submit" name = "submitButton" value = "submit">
</form>
Output:
This output will accept any credentials.
A form with the CSRF token will look like:
Code:
<form method = "post" >
{{ csrf_field() }}
<label> Email </label>
<input type = "text" name = "email"/>
<br/>
<label> Message </label>
<input type = "text" name = "message"/>
<input type = "submit" name = "submitButton" value = "submit">
</form>
Output:
The CSRF token will then look like this:
Examples of CSRF Token Laravel
Given below are the examples mentioned:
Example #1
Code:
<!DOCTYPE html>
<html>
<head>
<title>Laravel | CSRF Protection</title>
</head>
<body>
<section>
<h1>CSRF Protected HTML Form</h1>
<form method="POST">
@csrf
<input type="text" name="username"
placeholder="Username">
<input type="password" name="password"
placeholder="Password">
<input type="submit" name="submit" value="Submit">
</form>
</section>
</body>
</html>
Example #2
Code:
<!DOCTYPE html>
<html>
<head>
<title>Laravel | CSRF Protection</title>
</head>
<body>
<section>
<h1>CSRF Protected HTML Form</h1>
<form method="POST">
{{ csrf_field() }}
<input type="text" name="username"
placeholder="Username">
<input type="password" name="password"
placeholder="Password">
<input type="submit" name="submit"
value="Submit">
</form>
</section>
</body>
</html>
Example #3
Code:
<!DOCTYPE html>
<html>
<head>
<title>Laravel | CSRF Protection</title>
</head>
<body>
<section>
<h1>CSRF Protected HTML Form</h1>
<form method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="username"
placeholder="Username">
<input type="password" name="password"
placeholder="Password">
<input type="submit" name="submit"
value="Submit">
</form>
</section>
</body>
</html>
Output:
The output for all three state examples would be:
Example #4
Verification of CSRF token.
Code:
<?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 = [
//
];
}
[...]
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Illuminate\Session\TokenMismatchException
*/
public function handle($request, Closure $next)
{
if (
$this->isReading($request) ||
$this->runningUnitTests() ||
$this->inExceptArray($request) ||
$this->tokensMatch($request)
) {
return $this->addCookieToResponse($request, $next($request));
}
throw new TokenMismatchException;
}
[...]
Below is the output we get after running the above-mentioned codes.
Output:
The classic CSRF handling of error.
Code:
if( $exception instanceof TokenMismatchException){
return response()
->view('errors.401', ['error' => 'Page expired, go back and try again'], 401);
}
return parent::render($request, $exception);
}
[...]
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Error</div>
<div class="card-body">
@if ($error)
<div class="alert alert-danger">
{{ $error }}
</div>
@endif
</div>
</div>
</div>
</div>
</div>
@endsection
Output:
This is when no CSRF tokens are inserted.
However, once the SCRF token has been inserted.
Example #5
Code:
$ php artisan make:controller SendMoneyController
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class SendMoneyController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function send(Request $request)
{
$data = $request->validate([
'email' => 'required|email',
'amount' => 'required|numeric'
]);
$sender = auth()->user();
$recipient = User::where('email', $data['email'])->first();
$sender->charge($data['amount']);
$recipient->grant($data['amount']);
return redirect()->action('HomeController@index')
->withStatus("${$data['amount']} sent to {$recipient->name}");
}
}
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
<p>Wallet Balance : $ {{ $user->balance}}</p>
<form action="{{ url('/sendmoney')}}" method="post">
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Recipient's Email :</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="amount" class="col-md-4 col-form-label text-md-right">Amount :</label>
<div class="col-md-6">
<input id="amount" type="numeric" class="form-control" name="amount" required autofocus>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Send Money
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Output:
The tokens are the safeguards the framework has built to create a wall around the user. CSRF attacks can also create havoc with the backend of the systems. Hence the developer must build functionalities that create such walls.
Conclusion
As we have seen, cyber-attacks leave a rather bitter aftertaste. To avoid such, backend programming has to be strong enough to act as a deterrent. The intrepid developer has to find ways to use knowledge to come up against this invisible enemy. Luckily, Laravel Framework is there to assist all the way.
Recommended Articles
We hope that this EDUCBA information on “CSRF Token Laravel” was beneficial to you. You can view EDUCBA’s recommended articles for more information.