【问题标题】:Prevent users to access some routes in Laravel and Vue阻止用户访问 Laravel 和 Vue 中的某些路由
【发布时间】:2020-05-08 19:19:56
【问题描述】:

我正在使用 Laravel 和 Vue 构建一个 SPA,我不希望用户访问我尝试使用 Laravel 中间件的 /products/create 路由,但它没有帮助

这是我的 App.vue 组件

<template>
    <div>
        <Navbar :name="user.name"/>
        <router-view></router-view>
    </div>
</template>

<script>
    import Navbar from "./Navbar";
    export default {
        name: "App",

        props: [
            'user'
        ],

        components: {
            Navbar,
        },

        created() {
            window.axios.interceptors.request.use(config => {
                config.headers.common['Authorization'] = 'Bearer ' + this.user.api_token;
                return config;
            });
        },
    }
</script>

IsAdmin.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class IsAdmin
{
    public function handle($request, Closure $next)
    {
        if (! Auth::user()->isAdmin) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        return $next($request);
    }
}

如何将非授权用户重定向到 404 页面?

【问题讨论】:

  • 你在 laravel 中是怎么做的?您是否在每个用户中都使用角色?
  • “我尝试过使用 Laravel 中间件,但没有帮助” - 我在您的问题中没有看到任何中间件代码...如果您尝试过它并且它不起作用,包含该代码,以便我们可以看到您的方法出了什么问题。
  • 请分享你的代码:)(中间件)
  • 谢谢。我已经分享过了。

标签: laravel vue.js single-page-application


【解决方案1】:

您没有提供足够的信息,但我这样做的方式是使用Laravel policies

我会为这样的产品设置政策:

namespace App\Policies;

use App\Product;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class ProductPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can create products.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        return $user->hasPermissionTo('create products');
    }
}

在 App\Providers\AuthServiceProvider.php 中注册您的策略

protected $policies = [
        'App\Product' => 'App\Policies\ProductPolicy',
    ];

然后在您的产品控制器中,您需要添加它才能通过授权过程:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    public function store(Request $request)
    {
        $this->authorize('create', Product::class)
        // The current user is authorized to make this request.
    }
}

您可能希望阻止未经授权的用户访问您创建产品的 vue 路由。为此,您必须将用户权限传递给您的 vue 应用程序。

return [
    'name' => $user->name,
    'permissions' => [
        'createProducts' => $user->can('create', \App\Product::class)
    ]
}

然后在你的 vue 应用中:

<router-link v-if="user.permissions.createProducts" to="/products/create">
    New Product
</router-link>

【讨论】:

  • 但是如何将非授权用户重定向到 404 页面?我的用户表中有一个角色列。
  • 我看到您编辑了您的问题,如果您将中间件与 vue spa 和 axios 一起使用。您可以简单地捕获 tan 错误响应,然后将用户重定向到您的 vue 路由器中的未处理路由。 axios.post('/products', this.product).then(response =&gt; { //success }).catch(error =&gt; { if(error.response.status == 403){ //redirect to unauthenticated route. } });
  • 但我什至不希望用户访问创建产品页面,所以当有人尝试直接访问该路线时,我希望他们获得 404 页面
  • 由于您正在构建一个带有 laravel 后端的水疗中心,因此 laravel 一侧的中间件在更改路由时不会帮助您,因为所有路由更改都将由 vue 路由器处理,因此您必须实现类似kamal 的回答如下,但在您需要将用户的权限传递到您的 vue 应用程序之前,在这种情况下,我建议使用 vuex 来存储用户及其权限。
【解决方案2】:

vue 路由保护

为了保护 Vue 路由,您可以使用导航防护,它是 Vue Router 中的一个特定功能,它提供与如何解析路由有关的附加功能。

您必须使用 vue-router 包才能在 vuejs 应用中使用路由

src/router/index.js 中,您可以添加路由保护,如下所示

import Vue from "vue";
import Router from "vue-router";
import Main from "@/components/Main";
import Products from "@/components/Products";
import Create from "@/components/Create";
import Show from "@/components/Show";
import Unauthorised from "@/components/Unauthorised";

//use vue router 
Vue.use(Router);

//init Router and define some routes
export default new Router({
    routes: [
        {
            path: '/',
            name: 'Main',
            component: Main
        },
        {
            path: '/products',
            name: 'Products',
            component: Products
        },
        {
            path: '/create',
            name: 'Create',
            component: Create
        },
        {
            path: '/show',
            name: 'Show',
            component: Show
        },
        {
            path: '/unauthorised',
            name: 'Unauthorised',
            component: Unauthorised
        }

    ]
})

//apply route guard  
router.beforeEach((to, from, next) => {
//list of blocked routes
    const protectedRoutes = ['/products', '/create'];
//the route user is trying to access is in blocked routes list
    if (protectedRoutes.includes(to.path)) {
//redirect to route having unauhorised message page
        return next('/unauthorised');
    }
)
else
{
// otherwise allow user to access route
    return next();
}


在此示例中,有五个路由,即 //products/create/show 和最后一个 /unauthorised 以显示错误。在这里,如果任何用户尝试访问$protectedRoutes 中列出的路由,那么他们将被重定向到/unauthorised 路由,否则允许访问其他路由

您可以了解更多关于 vue 路由器保护 herevue-router here 的信息。此外,您可以根据用户角色或任何其他条件保护您的路由。我建议您使用 vuex根据存储在用户状态中的角色管理用户状态和管理路由访问

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    相关资源
    最近更新 更多