简体   繁体   中英

laravel 7 api CSRF token mismatch on POST request

Am I right that I need just to add api/* path to exception in /app/Http/Middleware/VerifyCsrfToken.php

<?php

namespace App\Http\Middleware;

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

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

See https://laravel.com/docs/8.x/csrf#csrf-excluding-uris

You should use api.php file for api routes, as they are not checked for csrf_token middleware by default in app/http/kernel.php :

protected $middlewareGroups = [
        'web' => [
          ...
            \App\Http\Middleware\VerifyCsrfToken::class,
          ...
        ],

        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

The mistake is, you've defined your api routes on routes/web.php , if you want to use /api from your root domain then make your API routes on routes/api.php .

routes/api.php :

Route::get('/test', function () {
    return 'Hello World';
});

Now you can access through http://127.0.0.1:8000/api/test

The web.php file contains routes that the RouteServiceProvider places in the web middleware group, which provides session state, CSRF protection, and cookie encryption. If your application does not offer a stateless, RESTful API, all of your routes will most likely be defined in the web.php file.

The api.php file contains routes that the RouteServiceProvider places in the api middleware group, which provides rate limiting. These routes are intended to be stateless, so requests entering the application through these routes are intended to be authenticated via tokens and will not have access to session state.

See the official documentation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM