向`api/user`请求未认证是什么原因?

问题描述 投票:0回答:1

我还是没明白。已经很多天了。

我正在仔细阅读这篇文章https://laravel.com/docs/11.x/sanctum#spa-authentication

文章指出,它们应该位于同一个顶级域,这很好。然而,我当前的设置涉及在一个域上使用 Laravel 作为 API,在另一个域上使用 ReactJS。

在本地,ReactJS 运行在 localhost:5173 上,而 Laravel 运行在 127.0.0.1:8000 上。

ReactJS

await axios.get('/sanctum/csrf-cookie', { headers: {
    'accept': 'application/json',
    'Content-Type': 'application/json'
  }})
  const response = await axios.post('/api/login', payload, { headers: {
    'accept': 'application/json',
    'Content-Type': 'application/json'
  }});
  if (response) {
    const responses = await axios.get('/api/user', {
      headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json'
      }
    });

    console.log(responses);
  }

前两个请求没问题,但第三个请求未经身份验证

    const responses = await axios.get('/api/user', {
      headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json'
      }
    });

为什么未经验证?

.env

SESSION_DOMAIN='.127.0.0.1:8000'
SANCTUM_STATEFUL_DOMAINS='localhost:5173'

cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie', 'login'],
'allowed_origins' => [http://localhost:5173'],
'supports_credentials' => true,

登录

    public function login(Request $request)
    {
        $validated = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($validated)) {
            $token = auth()->user()->createToken('auth_token');

            return response()->json([
                'token' => $token,
            ]);
        }

        return response()->json(['error' => 'Invalid credentials'], 401);
    }

请求

api/user
未通过验证的原因是什么?

你能提供解决方案吗?

php reactjs laravel laravel-sanctum
1个回答
0
投票

解决方案是Laravel和ReactJS应该在同一个顶级域下。经过大量阅读后,我了解到顶级域名是指

.com
.org
,并且我的设置明显区分了“localhost”和 IP“127.0.0.1”。

为了解决该问题,我创建了一个

.conf
文件,因为我使用的是 Apache2,并且我在同一域上设置了这两个配置。 对于反应js

<VirtualHost *:80>
    ServerName react.test

    ServerAdmin admin@localhost
    DocumentRoot /var/www/react/dist

    <Directory /var/www/react/dist/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

需要运行

pnpm run build

对于 Laravel

<VirtualHost *:80>
    ServerName api.react.test

    ServerAdmin admin@localhost
    DocumentRoot /var/www/laravel/public

    <Directory /var/www/laravel/public/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
© www.soinside.com 2019 - 2024. All rights reserved.