diff --git a/app/composables/useApi.ts b/app/composables/useApi.ts index 5d76f3d..d45db41 100644 --- a/app/composables/useApi.ts +++ b/app/composables/useApi.ts @@ -12,12 +12,21 @@ function readCookie(name: string): string | null { export function useApi() { const base = useRuntimeConfig().public.apiBase as string + const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']) + const api = $fetch.create({ baseURL: base, credentials: 'include', headers: { Accept: 'application/json' }, - onRequest({ options }) { - const xsrf = readCookie('XSRF-TOKEN') + async onRequest({ options }) { + const method = String(options.method || 'GET').toUpperCase() + let xsrf = readCookie('XSRF-TOKEN') + // Requête mutante sans cookie XSRF (ex : session ouverte via OIDC/pocket-id qui n'est jamais + // passée par /sanctum/csrf-cookie) → on pose le cookie avant, sinon Sanctum renvoie 419. + if (!xsrf && !SAFE_METHODS.has(method)) { + await ensureCsrf() + xsrf = readCookie('XSRF-TOKEN') + } const headers = new Headers(options.headers as HeadersInit) if (xsrf) headers.set('X-XSRF-TOKEN', xsrf) options.headers = headers