0

I have a vue SPA running on domain.co.uk and a laravel api running on api.domain.co.uk.

When I make a post request I get a CSRF mismatch error (419) because it isn't being sent in the header but instead as a cookie.

This is the code that sends the post request, using axios

axios.defaults.withCredentials = true;
axios.defaults.baseURL = 'https://api.domain.co.uk/';

export default class Api {
    constructor() {}

    async getCSRF() {
        return new Promise(async ( resolve, reject ) => {
            await axios.get( 'sanctum/csrf-cookie' )
            .then(( response ) => {
                resolve();
            }) 
            .catch(( error ) => {
                reject( error );
            })
        })
    }
    
    async login( email, password ) {
        return new Promise(async ( resolve, reject ) => {
            await axios.get( 'sanctum/csrf-cookie' ).then(( cookie ) => {
                await axios.post( 'login', { email: email, password: password } )
                .then(( response ) => {
                    resolve( response.data );
                })
                .catch(( error ) => {
                    reject( error.response.data );
                })
            })
            
        })
    }
}

I have set the session domain and stateful domains on the server. The env is

APP_URL=https://api.domain.co.uk
FRONTEND_URL=https://domain.co.uk
SESSION_DOMAIN=domain.co.uk
SANCTUM_STATEFUL_DOMAINS=domain.co.uk

The getCSRF request is successful and the XSRF-TOKEN and laravel_session cookies are set. But in the request the X-SRF-TOKEN header is not sent.

It works locally with the same setup, SPA running on localhost:5173 and api on localhost:8000.

Extra - even if i manually set the header i still get a mismatch

2
  • https://api.domain.co.uk and https://domain.co.uk are different origins. Try please add to config/cors.php 'allowed_origins' your spa origin https://domain.co.uk. I believe it should help. Commented Nov 1, 2023 at 16:32
  • it is added, laravel adds it as the FRONTEND_URL env variable to cors Commented Nov 1, 2023 at 17:54

1 Answer 1

0

Update your .env config to:

APP_URL=https://api.domain.co.uk
FRONTEND_URL=https://domain.co.uk
SESSION_DOMAIN=.domain.co.uk
SANCTUM_STATEFUL_DOMAINS=domain.co.uk,api.domain.co.uk
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.