Laravel 5-CSRF禁用方法和修改为cookie存储
CSRF攻击和漏洞的参考文章
http://www.cnblogs.com/hyddd/archive/2009/04/09/1432744.html
Laravel默认是开启了CSRF功能。
关闭此功能有两种方法
方法一
打开文件:app\Http\Kernel.php
'App\Http\Middleware\VerifyCsrfToken'//注释掉
方法二
打开文件:app\Http\Middleware\VerifyCsrfToken.php修改为:
<?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的代码中加入:
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
第二种
使用cookie方式。
使用cookie方式的CSRF,可以不用在每个页面都加入这个input的hidden标签。
使用cookie方式,需要把app\Http\Middleware\VerifyCsrfToken.php修改为:
<?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)); } }
只对GET的方式提交使用CSRF,对POST方式提交表单禁用CSRF
对指定的表单[提交方式]使用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; } }
修改CSRF的cookie名称方法
要修改这个名称值,可以到打开这个文件:vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php 找到”XSRF-TOKEN“,修改
/** * Add the CSRF token to the response cookies. * * @param \Illuminate\Http\Request $request * @param \Symfony\Component\HttpFoundation\Response $response * @return \Symfony\Component\HttpFoundation\Response */ protected function addCookieToResponse($request, $response) { $config = config('session'); $response->headers->setCookie( new Cookie( 'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']), $config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null ) ); return $response; }
也可以在app\Http\Middleware\VerifyCsrfToken.php文件中,重写addCookieToResponse()方法做到