【问题标题】:Vue Router and Laravel MiddlewaresVue 路由器和 Laravel 中间件
【发布时间】:2019-03-02 13:42:26
【问题描述】:

我的申请有不同的路线:

GET /game/{any}

此路由受 Laravel auth 中间件保护。 在这个 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 和令牌身份验证?

【问题讨论】:

    标签: javascript php laravel vue.js


    【解决方案1】:

    您应该使用 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
    

    【讨论】:

      猜你喜欢
      • 2020-12-25
      • 2017-03-28
      • 2021-02-08
      • 2020-07-28
      • 2018-11-30
      • 2017-12-16
      • 2020-12-09
      • 2018-02-13
      • 2019-11-04
      相关资源
      最近更新 更多