skip to Main Content

I’m trying to make a login page using nuxt.js as Front-end and Laravel for the API.

But after I take the csrf token from sanctum-cookie, i can’t use it because of "CSRF token mismatch." . And I don’t know what to do…

Laravel info:

APP_URL=http://localhost:8080
FRONTEND_URL=http://localhost:3000
SANCTUM_STATEFUL_DOMAINS=http://localhost:8000,localhost:3000,localhost:8000,http://localhost:3000

8080 is the port for LAravel and 3000 is nuxt.

Those are the calls to the api and the login is retarded and return an error about CSRF and I have no idea why.

// calls from nuxt
async function validate() {

  await axios.get('http://localhost:8080/sanctum/csrf-cookie', {
    withCredentials: true
  });

  const token = useCookie('XSRF-TOKEN');

  await axios.post('http://localhost:8080/login', {
    'email': '[email protected]',
    'password': '1234567890'
  }, {
    headers: {
      'X-XSRF-TOKEN': token.value as string
    }
  })
}

cors.php config

    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,

2

Answers


  1. Chosen as BEST ANSWER

    After 3 days ... all i need to do was to add withCredentials: true for the login axios...

    Awesome! <3


  2. set sanctumn.php :

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
            '%s%s',
            'localhost,localhost:3000,127.0.0.1,127.0.0.1:8080,::1',
            Sanctum::currentApplicationUrlWithPort()
        ))),
    

    then set env variable in .env file as given below:

    FRONTEND_URL=http://localhost:3000
    ROOT_URL=//127.0.0.1:8080
    APP_URL=http://localhost
    SESSION_DRIVER=cookie
    SESSION_DOMAIN=.localhost 
    

    then run these commands in laravel project:

    php artisan config:clear && php artisan cache:clear && php artisan optimize && php artisan serve
    

    then in your nuxt login.vue:

    async function validate() {
    
      await useFetch("http://localhost:8080/sanctum/csrf-cookie", {
        credentials: "include",
      });
    
      const token = useCookie('XSRF-TOKEN');
    
      await useFetch("http://localhost:8080/api/login", {
        credentials: "include",
        method: "POST",
        body: {
          'email': 'email',
          'password': 'password'
        },
        headers: {
          'X-XSRF-TOKEN': token.value as string,
        },
        watch: false
      })
    // remaining codes...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search