upthemedia/xss-protection

在输入中过滤xss

0.0.8 2020-12-14 21:52 UTC

This package is not auto-updated.

Last update: 2024-09-17 15:41:30 UTC


README

在Laravel项目中全局阻止XSS攻击。它可以以两种不同的方式使用。或者通过影响所有请求的中件,或者通过FormRequest

安装

composer

composer require upthemedia/xss-protection

配置

使用中件 要在项目全局使用,需要创建一个中件并将它添加到Kernel.php中的protected $middleware

<?php
namespace App\Http\Middleware;  
use Closure;
use Illuminate\Http\Request;
use Upthemedia\XssProtection\XssProtectionTrait;  
final class XssClean {  
    use XssProtectionTrait;  
    public function handle(Request $request, Closure $next)  
    {  
	    $input = $request->all();  
	    array_walk_recursive($input, function(&$input) {  
		    $input = $this->xss_clean($input);  
		});  
		$request->merge($input);  
		return $next($request);
	}
}

文件 Kernel.php

<?php  
namespace App\Http;  
use Illuminate\Foundation\Http\Kernel as HttpKernel;  

class Kernel extends HttpKernel{  
/**
* The application's global HTTP middleware stack.
* These middleware are run during every request to your application. 
* 
* @var array   
*/  
protected $middleware = [
     \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,  			
     \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,  
     \App\Http\Middleware\TrimStrings::class,  
     \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,  
     \App\Http\Middleware\XssClean::class  //Add Middleware XSS
      ];

在FormRequest中使用 要在FormRequest中使用,只需要导入XssProtectionTrait。在这种情况下,它将对所有输入执行清理xss。

<?php  
namespace App\Http\Requests;  
use Illuminate\Foundation\Http\FormRequest;
use Upthemedia\XssProtection\XssProtectionTrait;  
class StoreComment extends FormRequest  {  
    use XssProtectionTrait;  
    /**  
    * Determine if the user is authorized to make this request. * * @return bool  
    */  
    public function authorize()  {  
    return true;
    }  
    /**
    *Get the validation rules that apply to the request. * * @return array  
    */  
    public function rules() {  
	    return [  '
		    'comment' => 'require', 
		    'subject  => 'nullable'
		      ];
	}
}