用于API令牌身份验证的React + Laravel + Sanctum非cookie

问题描述

我正在尝试让React和Laravel使用中间件Sanctum一起工作。

我可以阅读许多人尝试使用基于cookie的设置来执行此操作的示例,但是我尝试将令牌设置用于纯API方法。之所以这样做,是因为我想准备后端以在没有Cookie的移动应用中使用。

这是我设置的一部分:

/backend/routes/api.PHP

Route::post('/login',[ UserController::class,'getAccesstoken'] );

/frontend/store/api.js

static login( user ) {

    var formData = new FormData();
    formData.append('username',user.username);
    formData.append('password',user.password )
    formData.append('deviceName','browser');

    return fetch( 
        'http://localhost:5001/api/login,{
            method : 'post',body : formData
        }
    );
}

我的问题是,当访问登录路由时,它会强制CSRF令牌检查。 即使登录路径不应该由Sanctum保护。 当我登录并且还没有令牌附加到请求时,这当然会失败。 据我了解,令牌仅在登录后访问受保护的路由时才需要。 我已经通过将其重命名为伪造并得到错误来再次检查它是否在访问正确的路由。

我在使用Sanctum时出现了问题吗?还是Sanctum并不是api令牌的首选用法?我应该代替JWT吗?

在此先感谢您的帮助。

解决方法

在:

/backend/app/Http/Kernel.php

我添加了:

\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

当我删除该行时,它起作用了。我无法理解SPA等于使用cookie,因为我会说我也在开发一个仅使用API​​令牌的SPA。

下一个问题是,我使用的是Doctrine而不是Eloquent,在发行令牌时,我现在可以看出它与Sanctum不兼容。但这将是另一个问题的话题。

,

请检查此URL,由于本教程,我能够使其正常工作。

https://laravel-news.com/using-sanctum-to-authenticate-a-react-spa

这是我的 LoginForm.jsx

import React from "react";
import apiClient from "./services/apiClient";

const LoginForm = (props) => {
  const [email,setEmail] = React.useState("");
  const [password,setPassword] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    apiClient.get("/sanctum/csrf-cookie").then((response) => {
      apiClient
        .post("/api/sanctum-token",{
          email: email,password: password,device_name: "React v0.1",})
        .then((response) => {
          console.log(response);
        });
    });
  };
  return (
    <div>
      <h1>Login</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="email"
          name="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
        <input
          type="password"
          name="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />
        <button type="submit">Login</button>
      </form>
    </div>
  );
};

export default LoginForm;

apiClient.js

import axios from "axios";

const apiClient = axios.create({
  baseURL: "http://localhost",withCredentials: true,});

export default apiClient;