Search code examples
javascriptlaravelvue.jsheaderauthorization

Token Authorization header with passport in vue.js


Where can i put the Authorization header token in axios after dispatching login action with laravel passport authentication in a seprated vue.js project?I tried with setting it in main.js like this and doesnt work properly. After dispatching, In the QuestionIndex component, the axios call dont have the authorization header automatically. And by refreshing the page, it has the authorization header. I can fix this by putting the token header in QuestionIndex Component. But I dont think this is a proper way to do it. Please help me with this problem. In main.js

const token = localStorage.getItem('access_token');
if (token) {
  axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}

In login.vue

login(){
             this.$store
                .dispatch("login", this.form)
                .then(() => {
                    this.$router.push({ name: "QuestionIndex" });
                })
                .catch(err => {
                    
                    console.log(err);
                });
        }

In vuex store

  state: {
        token: localStorage.getItem('access_token') || null,
        user: {},
    },
    mutations: {
        setToken(state, data) {
            state.token = data.token;
            state.user = data.user;
        },
       
    },
    actions: {
       
        login({ commit }, credentials) {
            return axios.post("http://127.0.0.1:8000/api/login", credentials).then(( res ) => {
                localStorage.setItem('access_token', res.data.data.token);
                commit("setToken", res.data.data);
            });
        },
    },
    getters: {
        token: (state) => state.token,
    
    }

Solution

  • You can set the Authorization header after initializing the axios instance like this:

    axiosInstance.interceptors.request.use((config) => {
      const token = localStorage.getItem('access_token');
      config.headers.Authorization = `Bearer ${token}`
    
      return config
    })
    

    In your VUEX action, make sure to use the axiosInstance you created in your main.js (or whereever). If you just import axios in your VUEX store like this import axios from 'axios' it will not work, because it's not the axios instance you set the header on.