【问题标题】:Laravel Sanctum/React on LAMP Stack - Unauthenticated but x-xsrf-token presentLaravel Sanctum/React on LAMP Stack - 未经身份验证但存在 x-xsrf-token
【发布时间】:2021-04-24 01:03:46
【问题描述】:

我在 LAMP Stack 上使用 Laravel Sanctum。我有我的前端反应应用程序指向 /var/www/app.example.com 和我的后端 Laravel 指向同一服务器上的 /var/www/appapi.example.com。两者都加载正常。

我目前正在构建本教程 - https://dev.to/dog_smile_factory/series/5857

如果您打开开发工具并遵循其工作流程,您可以注册一个新用户,登录,然后它会自动尝试访问 api/users 路由 - 始终返回 unauthenticated

即使一切尽我所能,我也没有通过 - 这就是我所拥有的:

CORS.php

'paths' => ['api/*', 'sanctum/csrf-cookie', '*'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

.env

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:2tD+oAGu+NOPE+NOPE+NOPE+gq9brRpfuKCL+t4M=
APP_DEBUG=true
APP_URL=appapi.example.com

LOG_CHANNEL=stack
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=apppue
DB_USERNAME=root
DB_PASSWORD=NopeNopeNope

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=cookie
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

SESSION_DOMAIN=.example.com
SANCTUM_STATEFUL_DOMAINS=.example.com

kernel.php

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/login', 'UserController@login');
Route::post('/register', 'UserController@register');
Route::get('/logout', 'UserController@logout');

在我的 React 应用上

所有的 axios 请求都是这样的(withCredentials = true):

axios.defaults.withCredentials = true;
// CSRF COOKIE
axios.get(hostName + "sanctum/csrf-cookie").then(
  (response) => {
    //console.log(response);
    // SIGNUP / REGISTER
    axios
      .post(hostName + "api/register", {
        name: userNameInput,
        email: userEmail,
        password: userPassword,
      })
      .then(
        (response) => {
          //console.log(response);
          // GET USER
          axios.get(hostName + "api/user").then(
            (response) => {
              //console.log(response);
              setUserId(response.data.id);
              setUserName(response.data.name);
              setErrorMessage("");
              setAuthStatus(LOGGED_IN);
            },
            // GET USER ERROR
            (error) => {
              setErrorMessage("Could not complete the sign up");
            }
          );
        },
        // SIGNUP ERROR
        (error) => {
          if (error.response.data.errors.name) {
            setErrorMessage(error.response.data.errors.name[0]);
          } else if (error.response.data.errors.email) {
            setErrorMessage(error.response.data.errors.email[0]);
          } else if (error.response.data.errors.password) {
            setErrorMessage(error.response.data.errors.password[0]);
          } else if (error.response.data.message) {
            setErrorMessage(error.response.data.message);
          } else {
            setErrorMessage("Could not complete the sign up");
          }
        }
      );
  },
  // COOKIE ERROR
  (error) => {
    setErrorMessage("Could not complete the sign up");
  }
);

};

x-xrfs-token 已根据我的判断正确保存,并随每个请求一起传入。也许我对此有误解,这就是为什么我无法访问经过身份验证的路线api/users

在几个教程、laravel 文档和网络搜索之后,我已经为此工作了 4 天 - 不知何故,我仍然遗漏了一些东西。大多数教程都在localhost 上执行此操作,我在 LAMP 堆栈上对其进行配置。这是我看到的唯一一件不同的作品。我做错了什么?

【问题讨论】:

    标签: php reactjs csrf laravel-sanctum x-xsrf-token


    【解决方案1】:

    经过几天的测试、阅读文档和其他教程(包括最有用的教程 - (https://laravel-news.com/using-sanctum-to-authenticate-a-react-spa))

    我发现了问题。

    SANCTUM_STATEFUL_DOMAINS=.example.com

    我完全不知道该放什么,测试它并证明它是正确/不正确非常困难。即使编辑供应商文件,我也无法将任何内容返回到我的前端应用程序 (app.example.com)。所有在线教程都是使用 localhost:3000 和 localhost:8000 开发的。然而,当在真实服务器上构建它时,这些 tuts 在这方面被证明是不够的 - 所以希望这对其他人有帮助!

    给我的答案:如果您能够登录到您的帐户但无法通过任何 auth:sanctum 中间件保护的路由,并且您将获得 XSRF-TOKEN cookie 和 laravel_session cookie(检查您的应用程序/存储开发人员选项卡(分别为 chrome/firefox))那么问题在于您在 SANCTUM_STATEFUL_DOMAINS 中列出的内容。我尝试输入https://app.example.comhttp://app.example.com、.example.com、example.com - 似乎都失败了。那么什么有效?

    app.example.com

    丢失 https、http,甚至可能是 www(老实说我没有测试这个),但请确保您列出了子域!

    【讨论】:

    • 这是一篇非常有帮助的帖子@jay - 本来可以在这呆上几天的 :)
    猜你喜欢
    • 2023-03-10
    • 2020-12-14
    • 2021-04-05
    • 2020-09-09
    • 2021-05-24
    • 2022-11-02
    • 2020-09-22
    • 2021-05-01
    • 2022-01-17
    相关资源
    最近更新 更多