Eu tenho CSRF token mismatch
erro somente para a solicitação POST de login. Meu projeto tem React v18.2.0 uma vez que frontend (hospedado no site da hostinger) e Laravel v10.10 uma vez que backend (hospedado no vps da hostinger) Inserir a url do frontend e do backend separadamente funciona muito. As solicitações GET corretamente fazem os dados carregarem na minha página inicial
O erro
{
"data": )XSRF-TOKEN=([^;]+)'));
return match ? match[2] : null;
,
"status": 419,
"statusText": "",
"headers":
const match = document.cookie.match(new RegExp('(^,
"config": {
"transitional":
const match = document.cookie.match(new RegExp('(^,
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env":
const match = document.cookie.match(new RegExp('(^,
"headers": {
"Accept": "application/json",
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
},
"baseURL": "https://srv545719.hstgr.cloud/",
"withCredentials": true,
"withXSRFToken": true,
"method": "post",
"url": "/login",
"data": "{"email":"[email protected]","password":"adminpassword"}"
},
"request": {}
}
Quando tento fazer login recebo o erro 419 "CSRF token mismatch."
É mal configurei meu backend
.env
APP_URL=https://backend-domain
FRONTEND_URL=https://frontend-domain
SESSION_DRIVER=database
SESSION_COOKIE=frontend-domain
SANCTUM_STATEFUL_DOMAINS=frontend-domain,backend-domain
SESSION_DOMAIN=frontend-domain
config/cors.php
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['https://frontend-domain', 'https://backend-domain'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
config/sessão.php
'driver' => env('SESSION_DRIVER', 'database'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION'),
'table' => 'sessions',
'store' => env('SESSION_STORE'),
'lottery' => [2, 100],
'cookie' => env(
Sua visita nos ajuda a continuar oferecendo o melhor para você! 'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => "https://stackoverflow.com/",
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE', false),
Sua visita nos ajuda a continuar oferecendo o melhor para você! 'http_only' => true,
'same_site' => 'none',
'partitioned' => false,
config/santuário.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS')),
'guard' => ['web'],
'expiration' => null,
'middleware' => [
'verify_csrf_token' => AppHttpMiddlewareVerifyCsrfToken::class,
'encrypt_cookies' => AppHttpMiddlewareEncryptCookies::class,
],
kernel.php
protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
IlluminateSessionMiddlewareStartSession::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
AppHttpMiddlewareVerifyCsrfToken::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
AppHttpMiddlewareLogCookies::class,
],
'api' => [
LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
IlluminateRoutingMiddlewareThrottleRequests::class.':api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
AppHttpMiddlewareLogCookies::class,
],
];
no frontend
AuthContext.jsx
const csrf = async () => {
try {
await axios.get("/sanctum/csrf-cookie");
} catch (error) {
console.error("Error fetching CSRF token:", error);
}
};
function getCsrfToken() )XSRF-TOKEN=([^;]+)'));
return match ? match[2] : null;
const axiosInstance = axios.create({
baseURL: 'https://backend-domain',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
withCredentials: true
});
const login = async ({ email, password }) => {
await csrf();
try {
const csrfToken = getCsrfToken();
const response = await axiosInstance.post(
"/login",
{ email, password },
{
headers: {
"X-XSRF-TOKEN": csrfToken,
},
}
);
navigate("/admin/");
await getUser();
} catch (error) {
console.error("Error during Sua visita nos ajuda a continuar oferecendo o melhor para você! error);
if (error.response.status === 422) {
setErrors(error.response.data.errors);
} else if (error.response.status === 403) {
console.error("Error:", error.response.data.message);
}
}
};
Se eu verificar os cookies salvos usando o devtools, não tenho nenhum cookie, acho que isso é secção do erro. Funcionou corretamente no localhost
Tags:
Crédito: Nascente Original