How to Fix Cross Site Scripting Vulnerability in Laravel

Hello Artisan,

How to create middleware for XSS protection in Laravel application is going to be today's tutorial. If you would like to protect sql injection in laravel applications, then it is necessary to enable XSS protection in your laravel app.

This laravel XSS protection example teaches you that how we can create our own custom middleware to protect our Laravel application from hackers. So if you don't know how to fix cross-site scripting vulnerability in PHP Laravel, then this example is for you.

So no need how to detect SQL injection, rather we will create a middleware that will be able to sanitize input field requests. You can say that this is the laravel security best practice as a developer.

So let's create and use XSS middleware to protect cross-site scripting vulnerability in Laravel:

 

Step 1: Create Middleware

In the first step, we need to create XSS middleware for protecting cross-site scripting vulnerability. To create it and update it like below:

App\Http\Middleware\XSS.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class XSS
{
    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 2: Register Middleware

Now we need to register this newly created middleware like below before using it:

\App\Http\Kernel.php

 protected $routeMiddleware = [
  'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
   .
   .
   .
   'XSS' => \App\Http\Middleware\XSS::class,
];

 

Now just use it in your route like:

routes/web.php

Route::group(['middleware' => ['XSS']], function () {
 Route::get('/home', 'HomeController@index')->name('home');
});

 

Read also: Example of Sending SMS to Mobile with Nexmo in Laravel

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js