Nuxt .js和Laravel API - CSRF令牌不匹配

e4eetjau  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(135)

我试图使用nuxt.js作为前端和Laravel的API做一个登录页面。
不幸的是,在我从sanctum-cookie中获取csrf令牌后,由于“CSRF令牌不匹配”,我无法使用它。我不知道从这里该怎么办。
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是LAravel的端口,3000是nuxt。
这些是对API的调用,登录时返回一个关于CSRF的错误,我不知道为什么。

// 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
    }
  })
}

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,
wz1wpwve

wz1wpwve1#

三天后...所有我需要做的是添加withCredentials: true为登录axios.
太棒了!<3

eyh26e7m

eyh26e7m2#

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()
    ))),

然后在.env文件中设置env变量,如下所示:

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

然后在laravel项目中运行这些命令:

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

然后在你的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...
}

相关问题