vuejs3laravel-sanctumlaravel-11

laravel 11 sanctum and vue 3 - 401 Unauthorized error


I am new to vue 3 and laravel sanctum. For one project I use laravel 11 sanctum for APIs and in another project I use vue 3 which uses that for clients. When logging in everything works fine except when I want to get the user info then it gives an error message.

enter image description here enter image description here enter image description here

  public function __invoke(Request $request)
    {
        $data = $request->validate([
           'email' => ['required', 'email'],
           'password' => ['required'],
        ]);

        $user = User::where('email', $data['email'])->first();

        if (!$user || !Hash::check($data['password'], $user->password)) {
            return response('Unauthorized.', 401);
        }

        $token = $user->createToken('auth_token')->plainTextToken;

        return response([
            'user' => $user,
            'token' => $token,
        ]);
    }
export default {

  setup() {

    const store = useStore()

    const login = () => {
      store.dispatch('login', {
        email: 'cassie81@example.com',
        password: 'password'
      })
    }
    return {login}
  }
}
import {createStore} from "vuex";
import axios from "axios";

export default createStore({

    state() {
        return {
            authenticated: false,
            user: null
        }
    },
    getters: {
        authenticated(state) {
            return state.authenticated
        },
        user(state) {
            return state.user
        }
    },
    mutations: {
        SET_AUTHENTICATED(state, authenticated) {
            state.authenticated = authenticated
        },
        SET_USER(state, user) {
            state.user = user
        }

    },
    actions: {
        authenticate({commit}) {
            axios.get('/api/user').then((response) => {
                commit('SET_AUTHENTICATED', true)
                commit('SET_USER', response.data)
            }).catch(() => {
                commit('SET_AUTHENTICATED', false)
                commit('SET_USER', null)

            })
        },

        async login({dispatch}, credentials) {
            await axios.get('/sanctum/csrf-cookie')
            await axios.post('/login', credentials)

            dispatch('authenticate')
        }
    }

})

Solution

  • Solved the problem!

    
    const login = async () => {
      await axios.get('/sanctum/csrf-cookie')
      const response = await axios.post('/login', form)
    
    axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`
      axios.get('/api/user').then((response) => {
        console.log(response)
      })
    }