0

I am using vue and laravel in a project, I have sanctum configured in laravel, when I update the page the data is deleted I get an Unauthorized message. I tried to set vuex-persistedstate in the project, but it doesn't work, I was also trying to create an interceptor to read the token that is stored in the localStorage but nothing.

The problem is when I reload the page again, the requests it makes to the api seem to be lost and you have to log in again, Unauthenticated shows me

I am using vuex.

configuration .env:

SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost
SESSION_DRIVER=cookie

Api url path configuration:

export default {
  state: {
    apiURL: 'http://localhost:8000/api',
    serverPath: 'http://localhost:8000',
  },
  mutations: {},
  actions: {},
}

General vuex settings:

import Vue from 'vue'
import Vuex from 'vuex'

// Modules
import ecommerceStoreModule from '@/views/apps/e-commerce/eCommerceStoreModule'
import app from './app'
import api from './api'
import appConfig from './app-config'
import verticalMenu from './vertical-menu'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    app,
    api,
    appConfig,
    verticalMenu,
    'app-ecommerce': ecommerceStoreModule,
  },
  strict: process.env.DEV,
})

This is a part of the login file configuration:

if (success) {
      axios.get('http://localhost:8000/api/auth/sanctum/csrf-cookie')
        .then(() => {
          axios.post('http://localhost:8000/api/auth/login', {
            email: this.userEmail,
            password: this.password,
          }).then(resp => {
            const login = resp.data
            const tokenOriginal = login.accessToken
            const token = tokenOriginal.replace(/["']/g, '')

            localStorage.setItem('accessToken', JSON.stringify(token))
            localStorage.setItem('refreshToken', JSON.stringify(token))

            axios.defaults.headers.common.Authorization = `Bearer ${token}`
            axios.defaults.headers.common.Accept = 'application/json'

            axios.get('http://localhost:8000/api/user')

              .then(response => {
                const user = response.data.data
                const { role } = user

                localStorage.setItem('userData', JSON.stringify(user))

                this.$ability.update(user.ability)

axios configuration file:

import axios from 'axios'
import store from '@/store/index'

export function http() {
  return axios.create({
    baseURL: store.state.api.apiURL,
  })
}

export function httpFile() {
  return axios.create({
    baseURL: store.state.api.apiURL,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

configuration file path:

export default {
  state: {
    apiURL: 'http://localhost:8000/api',
    serverPath: 'http://localhost:8000',
  },
  mutations: {},
  actions: {},
}

Services file:

import { http } from '../http_service'

// Inventory
export function getInventories() {
    return http().get('/store_inventory')
}
2
  • Firstly, I would recommend not hardcoding the domain/port for your axios calls. Secondly, have you added localhost:8000 to the SANCTUM_STATEFUL_DOMAINS domains?
    – Rwd
    Commented Nov 29, 2021 at 16:08
  • yes I already added it but it didn't work Commented Nov 30, 2021 at 21:53

2 Answers 2

0

sanctum login is depend on cookies not local storage you must add with_credential: true to axios options and it is good to use this library to make authintication https://www.npmjs.com/package/vue-sanctum

1
  • Adding withCredentials I get this: Request from other origin blocked: same origin policy prevents reading remote resource at 'http: // localhost: 8000 / api / cost_centers' (reason: credential is not supported if CORS header' Access-Control-Allow-Credentials ' it is '*'). Commented Nov 30, 2021 at 22:03
0

I solved it by adding the headers to the axios configuration:

import axios from 'axios'
import store from '@/store/index'

export function http() {
 return axios.create({
 baseURL: store.state.api.apiURL,
 headers: {
   'Content-Type': 'application/json',
   'Accept': 'application/json',
   'Authorization': `Bearer 
   ${localStorage.getItem('accessToken').replace(/['"]+/g, '')}`
  }
 })
}

I get the accessToken from the localstorage and every time the page is reloaded the information is refreshed and does not appear anymore unauthorized

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.