简体   繁体   English

如何使用 vue 和 laravel 在视图中自动将 Bearer 令牌获取到 axios 标头

[英]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:应用程序.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 “if”结束后出现问题

';' 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):在每个请求上,在 js 文件(不是 vue)上,比如你的 bootstrap.js 文件(因为它会更快加载):

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.它会将用户重定向到您的主页或用户需要重定向到的任何页面,并且 access_token 将在 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.剩下的最后一点是在用户注销时删除 localStorage access_token项,并可能使用拦截器捕获 401,以删除 access_token 并在令牌过期时重定向到 /login。

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如果您打算向不属于您的外部端点发出 axios 请求,您可能需要检查 401 的域以确保它是您的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 laravel 8 如何使用不记名令牌获取用户 ID - laravel 8 how to get user id using bearer token 如何从 Laravel 中的请求中获取承载令牌 - How to get Bearer token from a request in Laravel php 如何在 curl 获取请求 header 中使用不记名令牌? - php how to use bearer token in curl get request header? 如何使用ajax在LARAVEL中获取新的CSRF令牌 - How can I get new CSRF token in LARAVEL by using ajax 如何在vue 2应用程序和laravel中创建和匹配CSRF令牌 - How can I create and match CSRF token in vue 2 app and laravel 我如何使用jwt.auth middleware将令牌传递给标头不在体内的标题:laravel 5.6 - how I can pass the token to header not in body using jwt.auth middleware :laravel 5.6 如何使用 Laravel Passport 对请求进行身份验证,在查询字符串中而不是在标头中具有访问令牌? - How can I authenticate a request using Laravel Passport having the access token in query string instead of in header? Laravel + Vue Js:如何从Axios请求中获取响应时隐藏Bootstraps 4模式 - Laravel + Vue Js : How can i hide a bootstraps 4 modal on getting response from Axios request 我如何从Vue.js Axios返回Laravel中的数据 - How i return data in Laravel from Vue.js Axios 如何使用 laravel 中的 Vue axios 从数据库中获取数据? - How to fetch data from the DB using Vue axios in laravel?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM