Я установил Sanctum и настроил конфигурацию Cors, как в каждом учебнике. но почему-то токен CSRF не может быть передан или что-то в этом роде, я не знаю. Это также не работает в Postman.
Код: Выделить всё
FRONTEND_URL=http://localhost:3000
ROOT_URL=http://localhost:8000
APP_URL=http://localhost:8000
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1
SESSION_SAME_SITE=none
SESSION_SECURE_COOKIE=false
Код: Выделить всё
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(['user' => $user, 'token' => $token], 201);
}
Код: Выделить всё
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->statefulApi();
$middleware->append([
\Illuminate\Http\Middleware\HandleCors::class,
EnsureFrontendRequestsAreStateful::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
ShareErrorsFromSession::class,
VerifyCsrfToken::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
Код: Выделить всё
export const register = async (name: string, email: string, password: string, password_confirmation: string): Promise => {
// Step 1: Fetch CSRF token from Laravel
await useFetch('http://localhost:8000/api/sanctum/csrf-cookie', {
method: 'GET',
credentials: 'include', // Include credentials to get the CSRF cookie
});
// Step 2: Retrieve the XSRF-TOKEN from cookies
const token = useCookie('XSRF-TOKEN');
console.log(token);
if (!token.value) {
throw new Error('CSRF token not found. Make sure cookies are enabled.');
}
// Step 3: Make the registration request
const { data, error } = await useFetch('http://localhost:8000/api/register', {
method: 'POST',
credentials: 'include', // Include cookies in the request
body: {
name,
email,
password,
password_confirmation
},
headers: {
'X-XSRF-TOKEN': token.value as string, // Set the CSRF token in the headers
},
});
// Handle any errors from the API
if (error.value) {
throw new Error(error.value.data.message || 'An error occurred during registration');
}
// Return token or some data as per your API response
// @ts-ignore
return data.value.token || 'Registration successful';
Подробнее здесь: https://stackoverflow.com/questions/790 ... csrf-error