阻止用户访问 Laravel 和 Vue 中的一些路由

Oth*_*ane 2 laravel single-page-application vue.js

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

这是我的 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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Kam*_*eti 5

用于 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();
}


Run Code Online (Sandbox Code Playgroud)

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

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