Skip to content
Advertisement

Laravel Sanctum & React with Axios, POST return 419

I am have been very desperate for these few days because I seem can’t overcome this one simple problem.

I can not authenticate my SPA (react via Axios) powered by Sanctum Laravel

I have read the documentation and read man tutorials and questions. Some problems have I overcome.

Eventually, I stuck in this one :

My request has contained the X-CSRF-TOKEN, but it always returns a 419 “message: CSRF token mismatch.”

Here is the screenshot of my network page :

enter image description here enter image description here

As it can be seen, that the “login” post request has sent the CSRF token. On the second picture is the cookie tab of the same request.

But in the end, it returned 419

I’m currently at lost on what to do

Please help

Thank you very much

P.S. As I am currently lost, I don’t know which part of my code should I attach, so from saving you all from reading an abundant amount of useless parts of the code, I did not post them all on my initial question, but by all mean, please request which part of code should I attach to further clarify my problem

Attachment:

Laravel’s .env

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=false
SESSION_DOMAIN=.localhost
SANCTUM_STATEFUL_DOMAINS=localhost:3000,localhost:8000,127.0.0.1:3000,127.0.0.1:8000

My react axios function

export const sendLogin = (data) => {
    axios.defaults.withCredentials = true;
    const response = axios.get(apiUrl('sanctum/csrf-cookie','backend-non-api-route')).then(response => {
        return axios.post(apiUrl('user/login','backend-non-api-route'),data,{ 
            xsrfHeaderName: 'X-CSRF-Token',
            withCredentials: true
          });
    })
    return response;
}

note : The apiUrl() function just appends the Laravel’s URL

app/http/Kernel.php

    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
            AppHttpMiddlewareHandleInertiaRequests::class,
        ],

        'api' => [
            LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            //IlluminateSessionMiddlewareStartSession::class,
            'throttle:api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
    ];

    
    protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
    ];
}

Advertisement

Answer

try this:

export const sendLogin = (data) => {
    axios.defaults.withCredentials = true;
    const response = axios.get(apiUrl('sanctum/csrf-cookie','backend-non-api-route')).then(response => {
        return axios.post(apiUrl('user/login','backend-non-api-route'),data,{ 
            xsrfHeaderName: "X-XSRF-TOKEN", // change the name of the header to "X-XSRF-TOKEN" and it should works
            withCredentials: true
          });
    })
    return response;
}

EDIT: Reading the Sanctum Documentation I get this snippet of doc:

During this request, Laravel will set an XSRF-TOKEN cookie containing the current CSRF token. This token should then be passed in an X-XSRF-TOKEN header on subsequent requests, which some HTTP client libraries like Axios and the Angular HttpClient will do automatically for you. If your JavaScript HTTP library does not set the value for you, you will need to manually set the X-XSRF-TOKEN header to match the value of the XSRF-TOKEN cookie that is set by this route.

and this another answer says that you have to use only one of them both (X-CSRF-TOKEN and X-XSRF-TOKEN).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement