javascript - Laravel 和 Vue.js 身份验证

标签 javascript php laravel authentication vue.js

在我的 vue.js 应用程序中,我有一个登录系统。我的 main.js 如下所示:

import Vue from 'vue';
import NProgress from 'nprogress';
import Resource from 'vue-resource';
import Router from 'vue-router';
import App from './App.vue';
import Login from './components/Authentication/Login.vue';
import auth from './Services/Authentication/Auth';


Vue.use(Router);
Vue.use(Resource);

auth.checkAuth();

export var router = new Router({
    history: true
});

router.map({
    '/': {
        name: 'Login',
        component: Login,
        guest: true
    }
});

router.beforeEach((transition) => {    
    if (transition.to.auth && !auth.user.authenticated) {
        transition.redirect('/login');
    } else if (transition.to.guest && auth.user.authenticated) {
        transition.redirect('/');
    } else {
        transition.next();
    }
});

Vue.http.interceptors.push((request, next)  => {    
    NProgress.start();
    const token = auth.getToken();
    request.headers['Authorization'] = 'Bearer ' + token;
    request.headers['X-CSRF-TOKEN'] = document.querySelector('meta[name="token"]').content;

    request.respondWith(request.body);

    next((response) => {
        NProgress.done();

        if (response.status == 404) {
            router.go('/');
        } else if (response.status == 401 && response.data.refreshed_token) {
          // If you received 401 "Unauthorized" response
          // with a refreshed_token in the payload,
          // this means you've got to refresh your token
          auth.setToken(response.data.refreshed_token);
        }

        return response;
    });
});

因此,在每次请求时,我都会检查用户 auth.checkAuth(); 该函数如下所示 (Auth.js):

checkAuth () {
     var token || localStorage.getItem('jwt-token');

    if (!token) {
      return false;
    }

    Vue.http.get('/api/me')
      .then(({data}) => {
        this.user.id = data.id;
        this.user.name = data.name;
        this.user.email = data.email;
        this.user.role = data.role;
        this.user.authenticated = true;
      }, ({data}) => {
          router.go('/');
      });
  }

所以我的问题是,在我的 router.beforeEach -> auth.user.authenticated 中,我检查用户是否经过身份验证。但是因为 auth.checkAuth(); 的 promise 没有返回,所以 auth.user.authenticated 总是 false!

如何解决这个问题?

非常有帮助!

最佳答案

对于遇到同样问题的 future 用户

Vue.http.interceptors.push((request, next)  => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);
    next((response) => {
        if(response.status == 401 ) {//or add any error code you want here
            //Do another request for some endpoint here to get a fresh token and override your token variable
        }
    });
});

关于javascript - Laravel 和 Vue.js 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39878465/

相关文章:

javascript - 未找到 Travis CI Jest Preset react-native

javascript - 添加类以滚动链接并在单击时添加相同的类

php - Codeigniter:每次刷新页面时都会运行函数

php - Cassandra PHP 模块

javascript - 通过 ajax 登录和注册是否安全?

javascript - Docker运行,无法访问应用程序

php - mysql - 按字段排序无法正常工作

php - 如何在 fzaninotto/Faker 中更改生成文本的语言?

Laravel 工匠修补匠 : write command on multiple lines

php - hasmany 表中的 Laravel Dropzonejs 文件验证