简体   繁体   中英

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

I am trying to get the token of current user to get retrieve the 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 can I set the 'Authorization' header to auto get the current token of the authenticated user?

I tried local storage as showing below:

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 = [];
    });
},

and it didn't work as well.

What seems to be the problem?


UPDATE:

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';
}

There is a problem after "if" ends

';' expected.

What i would do,

on every request, on a js file (not vue), like your bootstrap.js file (because it will be loader sooner):

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

on your login function, when you login 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 home page or whatever page the user needs to be redirected to, and the access_token will be set on the localStorage.

The last bit remaining is deleting the localStorage access_token item when the user is logged out, and perhaps catching 401 with an interceptor, to delete access_token and redirect to /login on token expiration.

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);
    }
});

You perhaps will need to check the domain of the 401 to be sure it's yours, if you intent to make axios requests to external endpoints that are not yours

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM