In this article, we will see how to create middleware for XSS protection in laravel 9. Cross-site scripting is a type of security vulnerability that can be found in some web applications. XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users.
In laravel 9 we use middleware to prevent XSS attacks on website security. It's very necessary protection from XSS attacks or any other cyberattack on the website.
So, let's see laravel 9 create middleware for XSS protection, laravel 9 creates middleware and XSS protection in laravel 9.
The XSS filter through we can remove the HTML tag from our input value and also it's very important to remove the HTML tag for security. Input sanitization is a security protocol for checking, filtering, and cleaning data inputs from app users.
There are three main types of XSS attacks:
In this step, We have to create custom middleware for XSS prevention in laravel 9. So, copy the below command and run it on the terminal.
php artisan make:middleware XSS
Now, register the middleware in kernel.php.
app/http/kernel.php
class Kernel extends HttpKernel
{
protected $routeMiddleware = [
'XSS' => \App\Http\Middleware\XSS::class,
];
}
In this step, we can see a new file in app/Http/Middleware/XSS.php and then just put the below code in our XSS.php file. You can directly use strip_tags() in any input field of saving data in the controller.
<?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);
}
}
Now, we are using XSS middleware in our routes.php file
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Middleware\XSS;
use App\Http\Controllers\UserController;
Route::group(['middleware' => ['XSS']], function () {
Route::get('xss_prevention', [UserController::class,'xssPrevention']);
Route::post('xss_prevention_data_store', [UserController::class,'xssPreventionStore'])->name('xssPreventionStore');
});
You might also like: