Все, что я пытаюсь сделать, не работает с моим сценарием аутентификации из Laravel 11 и Nuxt 3.
Я установил Sanctum и настроил конфигурацию Cors, как в каждом учебнике. но почему-то токен CSRF не может быть передан или что-то в этом роде, я не знаю. Это также не работает в Postman.
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';
Все, что я пытаюсь сделать, не работает с моим сценарием аутентификации из Laravel 11 и Nuxt 3. Я установил Sanctum и настроил конфигурацию Cors, как в каждом учебнике. но почему-то токен CSRF не может быть передан или что-то в этом роде, я не знаю. Это также не работает в Postman. [code]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 [/code] Контроллер аутентификации Laravel 11: [code]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', ]);
return response()->json(['user' => $user, 'token' => $token], 201); } [/code] bootstrap/app.php: [code]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;
// 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'; [/code] };