Laravel禁用单路径的csrf_token

时间:2015-12-15 14:37:51

标签: php laravel laravel-5

我尝试为此路线禁用csrf_token

Route::post('checkTransaction' ,'TestController@verifyTransaction');

VerifyCsrfToken 课程内容:

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
            'checkTransaction/*'
    ];

    public function handle($request, Closure $next)
    {
        $regex = '#' . implode('|', $this->except_urls) . '#';

        if ($this->isReading($request) || $this->tokensMatch($request) || preg_match($regex, $request->path()))
        {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException;
    }
}

但是在这个动作之后我得到了这个错误:

TokenMismatchException

结果:

HTTP/1.0 500 Internal Server Error
X-Powered-By: PHP/5.5.30
Cache-Control: no-cache, private
Content-Type: text/html
Vary: Accept-Encoding
Date: Tue, 15 Dec 2015 14:39:13 GMT
Server: LiteSpeed
Connection: close

view source
Accept  
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding 
gzip, deflate
Accept-Language 
en-US,en;q=0.5
Connection  
keep-alive
Cookie  
XSRF-TOKEN=eyJpdiI6Im9KR1g0K2c1UkE4cnh6K2QweWxwdnc9PSIsInZhbHVlIjoiTGRDQWFTNGwwVmJnbk5NU0dUOWVLV0MzM
3ZzV2tLYUNoT2JjaUVxVjFyWTZOYzlXbERGenV2SWROeW1xNW4xUkw3SHc2UXBoY281V3o3RU10NG9iSFE9PSIsIm1hYyI6IjdlY2QxODQ0NjgwMWY2NTFiOTIwM2JlYTY5NDk3NTdkMjZkZjU4NjI4YjFiODk3NDY0NDcyZmZhZTU0YzhhNzAifQ
%3D%3D; laravel_session=eyJpdiI6ImpyeHVabzVFQVpMTnBRUmR5NkdDQXc9PSIsInZhbHVlIjoieEQ4SG9sdjNaQkxYRXhc
L0t4N3NUUUJOOWFjYURYV0x4VGdHV21rMkxRQTFHNFd4eXNjZTFmS3k5Y3JoUXEzQ2tWSHdLRmtBaUt3TmdOdWtsZ3NOam9RPT0iLCJtYWMiOiJkMDFkNDhkNzUxZGM1M2FjYzEyZDY0ZmY5NjJhYzMwMjA5Y2U0YTY0YjRjYzYwZjA4Mzc0NmI1ZjU5M2M2MDVjIn0
%3D
Host    
...
User-Agent  
Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:42.0) Gecko/20100101 Firefox/42.0

2 个答案:

答案 0 :(得分:1)

使用except数组键作为第二个参数调用控制器构造函数中的中间件以排除方法:

public function __construct()
{
    $this->middleware('csrf', ['except' => ['verifyTransaction']]);
}

答案 1 :(得分:0)

首先,您在 handle()方法的实现中引用 $ this-&gt; except_urls 而不是 $ this-&gt;除了< /强>

其次,您构建的正则表达式将无效 - 它评估为 #checkTransaction / *#,这意味着 checkTransaction 后跟任意数量的斜杠。如果你想让它发挥作用,你需要将它改为 #checkTransaction /.*#或者只是 #checkTransaction。*#

最后,您的中间件不会执行父中间件不会执行的任何操作。只需设置 $ except 属性就足够了 - parent的 handle()实现将完成所有其他操作。