Home  >  Q&A  >  body text

How to automatically get Bearer token to axios header in view using vue and laravel

I'm trying to get the current user's token to retrieve data like this:

async getUser() {
    const config = {
                headers: {
                    'Accept': 'application/json',
                    'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ...'
                }
            }
  await this.axios
    .get("/api/auth/testapi", config)
    .then((response) => {
      this.user = response.data;
    })
    .catch((error) => {
      console.log(error);
      this.user = [];
    });
},

How do I set the "Authorization" header to automatically obtain the authenticated user's current token?

I tried local storage like this:

async getUser() {
    const token = localStorage.getItem('access_token');
    const config = {
                headers: {
                    'Accept': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            }
  await this.axios
    .get("/api/auth/testapi", config)
    .then((response) => {
      this.user = response.data;
    })
    .catch((error) => {
      console.log(error);
      this.user = [];
    });
},

But the effect is not good.

where is the problem?


renew:

app.js:

require("./src/main.js");
import VueAxios from "vue-axios";
import axios from "axios";
Vue.use(VueAxios, axios);


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

loginSuccess(accessToken) {
localStorage.setItem('access_token', accessToken);
window.location.href = '/home';
}

Problems occur after the end of "if"

';' expected.


P粉459440991P粉459440991300 days ago496

reply all(1)I'll reply

  • P粉579008412

    P粉5790084122024-01-17 10:32:56

    What will I do,

    On every request, on a js file (not vue), e.g. bootstrap.js file (because it will load faster):

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

    On your login function, when you log in the user and retrieve the access token:

    loginSuccess(accessToken) {
        localStorage.setItem('access_token', accessToken);
        window.location.href = '/home';
    }
    

    It will redirect the user to your homepage or whatever page the user needs to be redirected to, and the access_token will be set on localStorage.

    The last bit left is to remove the localStorage access_token entry when the user logs out, and possibly catch the 401 using an interceptor to remove the access_token and redirect to /login when the token expires.

    window.axios.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        if (401 === error.response.status) {
            localStorage.removeItem('access_token');
            window.location.href = '/login'
        } else {
            return Promise.reject(error);
        }
    });
    

    If you plan to make axios requests to an external endpoint that is not owned by you, you may want to check the domain of the 401 to make sure it is your domain

    reply
    0
  • Cancelreply