CSRF攻擊和漏洞的參考文章:php
http://www.cnblogs.com/hyddd/archive/2009/04/09/1432744.htmlhtml
Laravel默認是開啓了CSRF功能,須要關閉此功能有兩種方法:laravel
打開文件:app\Http\Kernel.php瀏覽器
把這行註釋掉:cookie
'App\Http\Middleware\VerifyCsrfToken'
打開文件:app\Http\Middleware\VerifyCsrfToken.phpapp
修改成:this
<?php namespace App\Http\Middleware;
use Closure; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { // 使用CSRF //return parent::handle($request, $next); // 禁用CSRF return $next($request); } }
CSRF的使用有兩種,一種是在HTML的代碼中加入:spa
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
另外一種是使用cookie方式。3d
使用cookie方式,須要把app\Http\Middleware\VerifyCsrfToken.php修改成:code
<?php namespace App\Http\Middleware;
use Closure; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { return parent::addCookieToResponse($request, $next($request)); } }
使用cookie方式的CSRF,能夠不用在每一個頁面都加入這個input的hidden標籤。
固然,也能夠對指定的表單提交方式使用CSRF,如:
<?php namespace App\Http\Middleware;
use Closure; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { // Add this: if($request->method() == 'POST') { return $next($request); } if ($request->method() == 'GET' || $this->tokensMatch($request)) { return $next($request); } throw new TokenMismatchException; } }
只對GET的方式提交使用CSRF,對POST方式提交表單禁用CSRF
一般使用CSRF時,會往瀏覽器寫一個cookie,如:
要修改這個名稱值,能夠到打開這個文件:vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php
找到」XSRF-TOKEN「,修改它便可。
固然,你也能夠在app\Http\Middleware\VerifyCsrfToken.php文件中,重寫addCookieToResponse(...)方法作到。
另外,如須要對指定的頁面不使用CSRF,能夠參考以下文章:
http://www.camroncade.com/disable-csrf-for-specific-routes-laravel-5/