Vue路由器和Laravel中间件

时间:2018-09-26 17:47:42

标签: javascript php laravel vue.js

我的应用程序具有不同的路由:

GET /game/{any}

此路由受Laravel身份验证中间件保护。 在这个Laravel路线中,我想构建SPA并提供Vue路由器:

const routes = [
  { path: '/game/start', component: GameStart },
  { path: '/game/stats', component: GameStats }
]

我有不受任何Laravel中间件保护的“主要”路线

GET /{any}

整个Vue路由器如下:

const routes = [
      // Not protected URLs
      { path: '/', component: Main },
      { path: '/news', component: News },

      // Protected URLs
      { path: '/game/start', component: GameStart },
      { path: '/game/stats', component: GameStats }
    ]

所以我的问题是: 这样将后端和前端混合在一起是个好主意吗? 因为我假设'/ game / *'路由器在前端部分不受保护。

还是应该在前端使用Laravel Passport和令牌认证?

1 个答案:

答案 0 :(得分:0)

您应该在前端使用vue-router元和回调(beforeEach)使用Laravel Passport和令牌身份验证。

routes.js

...

export const routes = [
  { path: '/game/start', component: GameStart, meta: { requiresAuth: true } },
  { path: '/game/stats', component: GameStats, meta: { requiresAuth: true } },
  { path: '/signin', component: SigninPage },
  { path: '*', redirec: '/' }
];

router.js

import VueRouter from 'vue-router';
import { routes } from './routes';
import store from './store'

export const router = new VueRouter({
  routes,
  mode: 'history'
});

router.beforeEach((to, from, next) => {
  // you could define your own authentication logic with token
  let isAuthenticated = store.getters.isAuthenticated

  // check route meta if it requires auth or not
  if(to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({
          path: '/signin',
          params: { nextUrl: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router