3

I am making authentication with SvelteKit and Laravel. This is the flow i currently have:

  • User logs in with correct credentials.

  • User login route has no middleware enabled on the Laravel side.

  • This login request returns a JWT token, which gets send back to the Sveltekit server.

  • I set this token as a cookie using this code:

    const headers = {
      'Set-Cookie': cookie.serialize(variables.authCookieName, body.token, {
        path: '/',
        httpOnly: true,
        sameSite: 'lax'
      })
    }
    
    return {
      headers,
      body: {
        user
      }
    }
    
  • The cookie is correctly set after that, verified.

So the authentication is handled correctly. But now i want to send that cookie with Axios to the Laravel server and authenticate the user but that doesn't work. The Laravel server never receives the cookie. The Axios withCredentials setting also never sends that cookie to the Laravel server. How can i make it work so that the cookie header is sent with Axios to Laravel? I have 0 CORS errors in my browser so i don't think that is the issue.

My API Class in SvelteKit:

import axios from 'axios'
import { variables } from '$lib/variables'

const headers: Record<string, string | number | boolean> = {
  Accept: 'application/json',
  'Content-Type': 'application/json',
  'X-Requested-With': 'XMLHttpRequest'
}

class Api {
  constructor() {
    axios.defaults.baseURL = variables.apiUrl
    axios.defaults.withCredentials = true

    axios.interceptors.response.use(
        response => response.data,
        error => Promise.reject(error.response.data)
    )
  }

  get(url: string) {
    return axios.get(url, { headers })
  }

  post(url: string, data?: unknown) {
    return axios.post(url, data, { headers })
  }

  patch(url: string, data: Record<string, unknown>) {
    return axios.patch(url, data, { headers })
  }
}

const api = new Api()

export default api

My Userservice:

import api from '$core/api'

const resource = '/users'

const userService = () => {
  const getAll = async () => {
    return await api.get(resource)
  }

  return {
    getAll
  }
}

export default userService

The Index endpoint (routes/dashboard/index.ts)

import services from '$core/services'

export async function get() {
  return await services.user.getAll()
  .then(({ data }) => {
    return {
      body: { users: data.users }
    }
  }).catch((err) => {
    return {
      body: { error: err.message }
    }
  })
}

My Hooks.index.ts (maybe for reference)

import * as cookie from 'cookie'
import jwt_decode from 'jwt-decode'
import type { GetSession, Handle } from '@sveltejs/kit'
import type { User } from '$interfaces/User'

// This is server side
/** @type {import('@sveltejs/kit').Handle} */
export const handle: Handle = async ({ event, resolve }) => {
  const { jwt } = cookie.parse(event.request.headers.get('cookie') || '')
  if (jwt) {
    const { user } = jwt_decode<{ user: User }>(jwt)
    if (user) {
      event.locals.user = user
    }
  }
  return resolve(event)
}

export const getSession: GetSession = async (request) => {
  return {
    user: request.locals.user
  }
}

Can someone help or explain why Axios has no idea if the cookie is set or not, or how i can send the Cookie with the request to the Laravel Server?

Gobbin
  • 530
  • 3
  • 17

0 Answers0