Laravel disable csrf_token for single route

2019-09-17 03:21发布

问题:

I try to disable csrf_token for this route:

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

VerifyCsrfToken class content:

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

but after this action i get this error:

TokenMismatchException

Result:

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

回答1:

Call middleware in controller constructor with an except array key as its second argument to exclude a method:

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


回答2:

Firstly, you're refering to $this->except_urls in your implementation of handle() method instead of $this->except.

Secondly, the regular expression you'd build would be invalid - it evaluates to #checkTransaction/*#, which means checkTransaction followed by any number of slashes. If you want to make it work, you'd need to change it to #checkTransaction/.*# or just #checkTransaction.*#.

Lastly, your middleware does not do anything that parent middleware wouldn't do. It should be enough to just set the $except property - parent's handle() implementation will do all the rest.