【问题标题】:SPA, Middleware, and VueRouterSPA、中间件和 VueRouter
【发布时间】:2017-06-21 22:41:42
【问题描述】:

我正在开发一个使用 Vue2、VueRouter 和 Laravel 5.4 的项目。它是一个单页应用程序。用于 API 身份验证的 Laravel Passport(来自我的 Vue 组件的 AXIOS 调用)。

应用程序的大部分内容来自一个刀片文件(类似这样):

<?php
//styling and the like
//...
//components being loaded here
<router-view></router-view>

//pull in the app.js file with vue router instantiation and routes
<script src="..."></script>

所有组件和路由都定义在一个 app.js 文件中,该文件被拉到这个文件中。

通过此刀片文件服务的组件都需要身份验证;用户必须登录并注册。

但是,该应用程序将有一个可供非注册用户访问的页面。拥有该 URL 的任何人都可以访问该页面;但是,在获得对页面的访问权限之前,他们需要输入安全密码。

页面本质上是用户填写并提交的表单。它还会事先从数据库中提取一些数据,以填充页面上的一些详细信息。

我没有打算做任何这种性质的事情,也很难找到如何做的例子。虽然我对如何去做有一些想法,但这是我最好的猜测:

  1. 创建一个新的 JS 文件来承载一个新的路由器。
  2. 创建一个将承载router-view element 的新刀片文件。它将拉入新创建的 JS 文件。
  3. 将新创建的刀片文件的路由添加到web.php文件;创建中间件,该中间件将拦截对 URL test/{id} 的任何尝试访问。如果中间件检查成功,并且用户输入了有效的密码,中间件将传递查看资源的请求。否则,重定向错误。

web.php 文件:

//Route for those people who are taking a test
Route::get('/test/{id}', 'TestController@serveTest');

//The authenticate view
Route::get('/authenticate/{id}', 'TestController@serveAuthenticate')
            ->name('authenticate')
            ->middleware('auth.test');

测试控制器文件:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Test;

class TestController extends Controller
{
    public function serveTest(Request $request) {
        return View('layouts.test');
    }

    public function serveAuthenticate() {
        return View('authenticate');
    }
}

中间件:

<?php

namespace App\Http\Middleware;

use Closure;
use App\Test;

class verifyTestAccess {
    public function handle($request, Closure $next) {   
        //Calculate some conditions here
        //...

        //Direct user to the authentication view if some condition is true
        if($hasPasscode) {
            return redirect()->route('authenticate', ['id' => $request->route('id')]);
        }

        //Let user access resource since it must not be password protected
        return $next($request);
    }
}

新刀片文件:

<?php
//Load the one component
<router-view></router-view>

//pull in the protectedPage.js file with vue router instantiation and routes
//this is a different file than in the first blade view
<script src="..."></script>

这是一个好方法吗?我想这种方法存在一些问题,并且创建一个 vue-router 来拉入一个组件并不是最佳选择。

【问题讨论】:

    标签: laravel-5 single-page-application vuejs2 vue-router


    【解决方案1】:

    最佳做法是将前端和后端分开。由于您使用的是 Laravel Passport,因此您将使用 JWT 从 VueJS 登录用户。

    所以 Laravel 本质上将充当 API,这意味着它不应该持有任何状态。一切都将使用 access_token 进行检查(由 api 生成并提供给客户端)

    受限网页:

    • Laravel 将有一个中间件来检查用户是否可以检索信息(使用令牌)
    • VueRouter 将有一个导航守卫来防止用户访问受限页面(可以通过检查令牌是否存在或通过其他属性)

    【讨论】:

      猜你喜欢
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 2017-07-26
      • 2020-04-10
      • 2023-03-26
      • 2018-05-17
      相关资源
      最近更新 更多