'Laravel Sanctum Vue

I have some problems authenticating an user with Laravel Sanctum. I have installed everything as needed, with Vite and Vue 3 as a frontend. So here is the problem... when I login with laravel default auth everything is fine, and when I create request from Vue frontend like:

const AxiosInstance = axios.create({
            headers: {
                Accept: "application/json",
                "Access-Control-Allow-Origin": "*",
                "Content-Type": "application/json",
                "X-Requested-With": "XMLHttpRequest",
            },
            baseURL: "http://127.0.0.1:8000/",
            withCredentials: true,
        });

The real problem is, when I try to get the user, it will always return Unauthenticated:

const user = async() => {
            await AxiosInstance.get('api/user')
        }

So User will be unauthenticated even if it's created directly from axios. I'm checking when user is logged in, and laravel will recognize something like:

        @guest
            <h1>Welcome guest</h1>
        @else
            <h1>Welcome user</h1>
        @endauth

But why api/user is not authenticated?



Solution 1:[1]

It because laravel scantum use Bearer token

Just change you axios instance like This

import axios from "axios";

const token = localStorage.getItem('auth_token')
 const api = axios.create({
    baseURL: 'http://127.0.0.1:8000/api/v1/',
    timeout: 1000,
    headers: {
        'Accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
  });

  export default api

I hope its helps you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saravana Sai