Introduction to CSRF Token Laravel
The following article provides an outline for CSRF Token Laravel. The worldwide web, even though a wonderful 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 into the system, then all hell may break loose. Identities may be stolen, 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 inkling differentiating between a genuine site asking for donations about education for poor kids or a site created mainly to gain illegal access to someone’s credit card or banking information. This kind of attacks is termed as CSRF or Cross-Site Forgery attacks.
These are vicious attacks that can debilitate and needs to be taken care of 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 which allows the user to create functionalities, which can withstand the rigours of modern-day consumer usage. The Laravel Framework also has expressive query command line system which enables the programmer to build services quickly and effortlessly. Since it is an open framework, Laravel allows third party programs and frameworks to be integrated into its systems. This is also one of the reasons why the Laravel Framework is sought after by ecommerce creators and owners. The Laravel Framework is also mindful of the kind of 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 the 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 time and tested mechanism to fight against such attacks are to create a layer of authentication which is going to be system generated. The tokens are the safeguards that the framework has built to create a wall around the user. CSRF attacks can also create havoc with the backend of the systems. Hence it imperative for the developer to build functionalities that create such walls.
Conclusion
As we have seen, cyber-attacks leave a rather bitter after taste. 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 one up against this invisible enemy. Luckily, Laravel Framework is there to assist all the way.
Recommended Articles
This is a guide to CSRF Token Laravel. Here we discuss the introduction to CSRF Token Laravel along with examples respectively. You may also have a look at the following articles to learn more –
600+ Online Courses | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6
View Course
Related Courses