How To Create Middleware For XSS Protection In Laravel 8

10-Apr-2023

.

Admin

How To Create Middleware For XSS Protection In Laravel 8

Hi Dev,

Today now in this post i will i how to create middleware for XSS protection in laravel.

XSS(Cross Site Scripting) protection is must need in our site because if we do not XSS protection then our site is not the secure.

The XSS filter through we can remove the html tag from our input value and also it's very important to remove html tag for the security.

In our laravel application we can implement it by using middleware concept in our project.

So here i will show you how to create XSS filter middleware in our laravel application by using following steps.

At first fire following command and need to create middleware:

Step : 1 Create Middleware


In this step, We have to create custom middleware in laravel based project. So let’s open your command prompt and run below command :

php artisan make:middleware XSS

Step : 2 Register Middleware

After successfully create middleware, go to app/http/kernel.php and register your custom middleware here :

app/Http/Kernel.php

class Kernel extends HttpKernel

{

protected $routeMiddleware = [

'XSS' => \App\Http\Middleware\XSS::class,

];

}

Step : 3 Implement logic In Middleware

Then now, we can see new file in app/Http/Middleware/XSS.php and then just put the bellow code in our XSS.php file.

<?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Http\Request;

class XSS

{

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed

*/

public function handle(Request $request, Closure $next)

{

$input = $request->all();

array_walk_recursive($input, function(&$input) {

$input = strip_tags($input);

});

$request->merge($input);

return $next($request);

}

}

Step : 4 Route

So now we are ready to use XSS middleware in our routes.php file, in bellow routes.php file we can do on that way:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Middleware\XSS;

use App\Http\Controllers\TestController;

Route::group(['middleware' => ['XSS']], function () {

Route::get('customVali', [TestController::class,'customVali']);

Route::post('customValiPost', [TestController::class,'customValiPost'])->name('customValiPost');

});

I hope it help you...

#Laravel 8

#Laravel 7

#Laravel

#Laravel 6