0

I'm trying to protect some routes, adding the CSRF verification that Laravel brings by default, I'm using Laravel v8 with sanctum, I have some APIs and I want to and tried to apply this security but I always get the same error: CSRF token mismatch.

This is my file .env:

SESSION_DRIVER=cookie
APP_DOMAIN_NAME=api.app.localhost
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=true
SESSION_DOMAIN=api.app.localhost
SANCTUM_STATEFUL_DOMAINS=https://api.app.localhost,localhost:3000,localhost:8000,127.0.0.1:3000,127.0.0.1:8000,localhost
SANCTUM_STATEFUL_DOMAINS=localhost:3000,localhost:8000,127.0.0.1:3000,127.0.0.1:8000,localhost

File VerifyCsrfToken:

class VerifyCsrfToken extends Middleware
{
    protected $addHttpCookie = true;
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'telescope/*',
        'sanctum/csrf-cookie'
    ];
}

File session.php:

'driver' => env('SESSION_DRIVER', 'cookie'),

'encrypt' => true,

File Kernel.php:

protected $middlewareGroups = [
 'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        \App\Http\Middleware\ForceJsonResponse::class,
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'csrf' => \App\Http\Middleware\VerifyCsrfToken::class,
    ];

Routes api.php:

for those routes I am applying the csrf middleware, but I always get the same error: CSRF token mismatch.

Route::post('auth/register', [AuthController::class, 'register'])->middleware('csrf');
Route::post('auth/login', [AuthController::class, 'login'])->middleware('csrf');
Route::get('user', [AuthController::class, 'user'])->middleware('csrf');

I am sending the csrf token by headers from postman like this:

X-CSRF-TOKEN. but it does not take it or apparently I am missing something to configure, and trying to create a test code to automatically store the XCSRF but nothing, first I call this route, so that it stores the csrf token: sanctum/csrf-cookie and then I call the routes where I apply the middlware sending the csrf by headers but it still doesn't work

1 Answer 1

0

Postman needs specific configuration to run with Laravel API. You have to add pre-request script to Postman.

pm.sendRequest({
    url: 'http://localhost:8000/sanctum/csrf-cookie',
    method: 'GET'
}, function (error, response, { cookies }) {
    if (!error) {
        pm.environment.set('xsrf-cookie', cookies.get('XSRF-TOKEN'))
    }
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.