Nuxt3 с Laravel 11 и ошибкой CSRF аутентификации SactumPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Nuxt3 с Laravel 11 и ошибкой CSRF аутентификации Sactum

Сообщение Anonymous »

Все, что я пытаюсь сделать, не работает с моим сценарием аутентификации из Laravel 11 и Nuxt 3.
Я установил 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
Контроллер аутентификации Laravel 11:

Код: Выделить всё

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);
}
bootstrap/app.php:

Код: Выделить всё

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();
Метод регистрации Nuxt3:

Код: Выделить всё

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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»