Remove Csrf verification of a specific route

I am trying to create an api with my laravel application, but when I submit a route request, Laravel by default tries to check the csrf token. So, I want to remove this check for api routes. I want to keep checking for the request to the foreground. But when I add exception routes to app / Http / Middleware / VerifyCsrfToken.php, I get this error:

block_exception clear_fix

this is VerifyCsrfToken.php

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
        'log_bounces_complaints',
    ];
}
+4
source share
2 answers

According to the Laravel documentation:

" VerifyCsrfToken, , , , ."

, " " , .

https://laravel.com/docs/5.2/routing#csrf-protection

, route.php

Route::group(['middleware' => 'web'], function () {
    // all your routes will go through CSRF check
}


// Anything outside will not go through the CRSF check unless you 
// define a middleware when constructing your controller.

Route::post('ajax', 'YourController@yourFunction');
+3

VerifyCsrfToken URL-, .

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken {

    protected $except_urls = [
        'your_specific_url/new_url',
        'your_specific_url/new_url_2',
        ...
    ];

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

}

.

protected $middleware = [

    ...

    'App\Http\Middleware\VerifyCsrfToken',
];
+4

Source: https://habr.com/ru/post/1628234/


All Articles