Home  >  Q&A  >  body text

Laravel Sanctum & NuxtJS SPA cannot create csrf cookie in browser

I have a backend API with Sanctum in Laravel and a separate repository SPA in NuxtJS

I'm trying to verify my SPA with Sanctum. I'm trying to follow the Sanctum documentation to get the CSRF cookie in the browser.

The problem is that when I call the CSRF token endpoint provided by Sanctum, I get the correct response, but the cookie is not set. That's it, no errors. It doesn't matter if I want to use nuxt auth or just plain old axios calls.

This is what I have:

Domain name: API -publisher.local:8080; front-end-publisher.local:3000

NUXT Authentication Configuration

auth: {
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: 'http://publisher.local:8080',
        endpoints: {
          login: { url: '/api/v1/login', method: 'post' },
          // logout: { url: '/auth/logout', method: 'post' },
          // user: { url: '/auth/user', method: 'get' }
        }
      },
    },
  },

AXIOS Configuration

axios: {
    baseURL: 'http://publisher.local:8080/api/v1', // Used as fallback if no runtime config is provided
    credentials: true,
    proxy: true,
  },

sacred.php

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

Session.php

'domain' => env('SESSION_DOMAIN', '.local'),

I tried different combinations and variations of these settings, but none worked. Do you guys know what could be wrong?

P粉512363233P粉512363233334 days ago548

reply all(1)I'll reply

  • P粉311563823

    P粉3115638232023-12-14 00:56:05

    I think I've figured this out. I made it work.

    So .local cannot be a top level domain, I think that might be part of the problem, but I'm not sure.

    Changing the domain name to the old localhost will solve the problem, but there is a problem with this solution. For some reason I don't know, I automatically get the XSRF cookie on any call to the API, no matter which endpoint I call. strangeness.

    The most effective way is to change the domain name to api.publisher.com and publisher.com, and then change all settings in the Sanctum document.

    Be extra careful with domain names to make sure they match and are set up correctly. It's very easy to reconfigure that thing, but hard to diagnose it!

    Hope it helps!

    reply
    0
  • Cancelreply