1

Laravel sanctum has been a bit of a headache for me as i have spent hours trying to figure out why sanctum/csrf-cookie route returns no content. initially the same route return 404 not found but after adding 'prefix' => 'api/sanctum' config/sanctum.php it seems to work except that it outputs nothing and no cookie is set in my browser.

Here are some of my codes

.env

SANCTUM_STATEFUL_DOMAINS=localhost:8080
SPA_URL=http://localhost:8080
SESSION_DOMAIN=localhost

--config/cors.php

'paths' => [
        'api/*',
        'login',
        'logout',
        'register',
        'user/password',
        'forgot-password',
        'reset-password',
        'sanctum/csrf-cookie',
        'user/profile-information',
        'email/verification-notification',
      ],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

axios

export const authClient = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  withCredentials: true, // required to handle the CSRF token
});

and having done all of that, if i tried to generate a token using

axios.get('/sanctum/csrf-cookie').then(response => {
    // Login...
});

i get 204 no content response i have also added the api middleware in kernel.php as instructed in the doucmentation but still wont set the cookie. and when i try to make request to another route protected by sanctum i 419 token mismatch. i have also run a fresh installation of laravel, php artisan optimize, cleared my brower history, checked the endpoints in postman but still thesame 204 and 419 exceptions

1
  • What is your VUE_APP_API_URL, is it localhost:8000? Commented May 13, 2022 at 23:07

6 Answers 6

7

I was struggling with the same issue for days and then founded a way that worked. so :

The '/sanctum/csrf-cookie' route return a 204 response when successfull, the then you have to send your post request with credentials. i used to get a 419 reponse status.

so after followed laravel docs here is what i added :

  1. SPA make sure you set the withCredentials header to true
  2. API

.env

SESSION_DRIVER=cookie
SESSION_DOMAIN='.localhost'
SANCTUM_STATEFUL_DOMAINS='localhost,127.0.0.1'

.kernel.php

add in your middleware array : \Illuminate\Session\Middleware\StartSession::class

Sign up to request clarification or add additional context in comments.

1 Comment

It works, but needed to change '.localhost' to 'localhost' without '.' in front. Worked without StartSession::class in kernal.php api. Needed to uncomment EnsureFrontendRequestsAreStateful in kernal.php
1

Hey I don't know whether you've found the answer or not but that request meant to have empty response body. Your CSRF token is available in the header of the response ;D

Comments

1

Note that the /sanctum/csrf-cookie route by default uses the middleware group web as defined by $middlewareGroups in \App\Http\Kernel.php.

Make sure that this middleware group contains \App\Http\Middleware\VerifyCsrfToken::class, because this is the middleware that actually sets the XSRF-TOKEN cookie.

If you are using a middleware group with a different name: You can't change the middleware used by the Sanctum route at the moment, so it is probably easiest to disable the default route by adding 'routes' => false to your config/sanctum.php file:

<?php

return [
   ...
   'routes' => false,
   ...
];

Then add a new route to your routes/web.php that doesn't have to return anything:

Route::get('/my/csrf', function(\Illuminate\Http\Request $request) {
    if ($request->expectsJson()) {
        return new JsonResponse(null, 204);
    }

    return new Response('', 204);
});

You should also place this route outside of any authentication, so it can be called before login.

Comments

0

From HTTP Specification:

The HTTP 204 No Content success status response code indicates that a request has succeeded, but that the client doesn't need to navigate away from its current page. This might be used, for example, when implementing "save and continue editing" functionality for a wiki site.

According to specification 204 is the exptected response from server.

Comments

0

You can insert in bootstrap.js file

import axios from 'axios';
window._ = _;


window.axios = axios;
window.axios.defaults.baseURL = "/api/";
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Comments

0

I was also facing the same issue in my reactjs app, I fixed this issue by sending the following

axiosClient.defaults.withCredentials = true;

I hope this will help.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.