Home  >  Article  >  Backend Development  >  How to create middleware for XSS defense in laravel 5?

How to create middleware for XSS defense in laravel 5?

藏色散人
藏色散人Original
2019-03-02 11:45:043597browse


XSS filters can remove html tags from input values, so it is important to remove html tags for security reasons. In laravel 5.2 this can be achieved by using middleware concept in your project.

How to create middleware for XSS defense in laravel 5?

Now I will introduce to you how to create XSS filtering middleware in laravel application.

First launch the following command and create the middleware:

Create middleware

php artisan make:middleware XSS

Now, you can create the middleware in app/Http/Middleware /XSS.php and place the following code into your XSS.php file.

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

Finally, the middleware must be registered in the app/Http/Kernel.php file. And add the following lines in the $routeMiddleware array.

Kernel.php

class Kernel extends HttpKernel
{
	....
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        ....
        'XSS' => \App\Http\Middleware\XSS::class,
    ];
}

Now you can use XSS middleware in your routing .php file. In the following routing .php file you can do this :

routes.php

Route::group(['middleware' => ['XSS']], function () {
  Route::get('customVali', 'CustomValDemoController@customVali');
  Route::post('customValiPost', 'CustomValDemoController@customValiPost');
});

Related laravel video tutorial: "Latest laravel mall practical video tutorial"

Related blog Recommended: "Defense against SQL Injection and XSS Attacks"

This article is an introduction to the method of creating middleware for XSS defense in laravel 5. I hope it will be useful to friends who need it. help!


The above is the detailed content of How to create middleware for XSS defense in laravel 5?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn