0

I get a status error code when I try to access the data after logging in. I am getting the XRSF token when someone attempts to log in but can't the user data back.

Below is my useAuth.js code

import axios from 'axios'

export default function useAuth() {

    const login = async (credentials) => {
        await axios.get('/sanctum/csrf-cookie') // ! STATUS CODE - 204 - Ok
    
        await axios.post('/login', credentials) // ! STATUS CODE - 200 - Ok

        let response = await axios.get('/api/user')
        console.log(response)                   // ! STATUS CODE - 401 - UNATHORIZED
    }


    return {
        login
    }

}

My routes/api.php code

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;


Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

My .env

SESSION_DRIVER=file
SESSION_LIFETIME=120

SANCTUM_STATEFUL_DOMAINS=localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1

I tried to change SESSION_DRIVER to cookie but brings the same result as file

Main App.vue code

<template>
  <form v-on:submit.prevent="login(form)">
    <div>
      <label for="email">Email</label>
      <input type="text" name="email" id="email" v-model="form.email">
    </div>
    <div>
      <label for="password">Password</label>
      <input type="password" name="password" id="password" v-model="form.password">
    </div>
    <div>
      <button type="submit">submit</button>
    </div>
  </form>
</template>

<script setup>
  
  import { reactive } from 'vue'
  import useAuth from './auth/useAuth'

  const { login } = useAuth()

  const form = reactive({
    email: '',
    password: ''
  })

</script>

Anyone with an idea on how I can solve the problem

Thank you

3 Answers3

0

I think you forget to send your token in Authorization header in this request

let response = await axios.get('/api/user')

So you must add your bearer token to authorization header like this:

axios.defaults.headers.common['Authorization'] = `Bearer your_token`;
  • Thanks for that answer, but i tried that. Can you please also show how you can set the Xsrf token on the headers because that is where the problems come from. You example is on how i can set the JWT_token – Tukei David Sep 15 '22 at 13:18
0

You also need to tell axios to include cookies when sending requests:

axios.defaults.withCredentials = true;

Also make sure cors.php has support_credentials set to true.

cdruc
  • 574
  • 2
  • 10
0

Thought this might help, I did get an answer to this question after much research. Silly me

SANCTUM_STATEFUL_DOMAINS=localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1

The above code should be set to the exact domain port.

You can check for further assistance on the link below

Getting 401 unauthorized for Laravel sanctum

MR_AMDEV answer.

Your all welcome