How to create middleware for XSS protection in Laravel?

How to create middleware for XSS protection in Laravel?

In this post we will give you information about How to create middleware for XSS protection in Laravel?. Hear we will give you detail about How to create middleware for XSS protection in Laravel?And how to use it also give you demo for it if it is necessary.

XSS(Cross Site Scripting) protection must need in your site because if you do not XSS protection then your site is not secure. XSS filter through you can remove html tag from your input value and it is very important to remove html tag for security. in your laravel 5.2 application you can implement by using middleware concept in your project. so how to create XSS filter middleware in your laravel application by using following step.

First fire following command and create middleware:

Create Middleware

php artisan make:middleware XSS

Now, you can see new file in app/Http/Middleware/XSS.php and just put bellow code in your XSS.php file.

XSS.php

namespace AppHttpMiddleware;

use Closure;

use IlluminateHttpRequest;

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);

}

}

At last you have to register your middleware in your app/Http/Kernel.php file. and add following line in $routeMiddleware array.


Kernel.php

class Kernel extends HttpKernel

{

....

protected $routeMiddleware = [

'auth' => AppHttpMiddlewareAuthenticate::class,

....

'XSS' => AppHttpMiddlewareXSS::class,

];

}

Now you are ready to use XSS middleware in your routes.php file, in bellow routes.php file you can that way:

routes.php

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

Route::get('customVali', 'CustomValDemoController@customVali');

Route::post('customValiPost', 'CustomValDemoController@customValiPost');

});

Hope this code and post will helped you for implement How to create middleware for XSS protection in Laravel?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  85  =  89

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US