php Laravel 5 的角色,如何只允许管理员访问某些根

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29060925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:13:14  来源:igfitidea点击:

Roles with laravel 5, how to allow only admin access to some root

phplaravel-5

提问by Vladimir Djukic

I follow this tutorial : https://www.youtube.com/watch?v=kmJYVhG6UzMCurrently I can check in my blade if user is a admin or not like this:

我按照本教程进行操作:https: //www.youtube.com/watch?v=kmJYVhG6UzM目前,如果用户是管理员或不是这样,我可以检查我的刀片:

{{ Auth::user()->roles->toArray()[0]['role'] }}
HI ADMIN
@endif

How can I make my route only available for admin user?

如何使我的路线仅对管理员用户可用?

回答by Chris Townsend

You need to create a middleware for your route.

您需要为您的路由创建一个中间件。

Use: php artisan make:middleware AdminMiddleware.

用途:php artisan make:middleware AdminMiddleware

You will find in your middleware folder a new file with this name.

您将在中间件文件夹中找到一个具有此名称的新文件。

Put your logic in your middleware, e.g.

将您的逻辑放在中间件中,例如

public function handle($request, Closure $next)
{
    if(Auth::check())
    {
        return $next($request);
    }
    else
    {
        return view('auth.login')->withErrors('You are not logged in');
    }

}

Once you have done your logic in your middleware, you can either call it in the route or make the middleware apply to all routes.

在中间件中完成逻辑后,您可以在路由中调用它或使中间件应用于所有路由。

If you want to add it to all routes, go to Kernel.phpand add it to the $middlewarearray, e.g.

如果要将其添加到所有路由,请转到Kernel.php并将其添加到$middleware数组中,例如

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',
    'App\Http\Middleware\VerifyCsrfToken',
    'App\Http\Middleware\AdminMiddleware',
];

If you want to add it to specific routes only, add it to the $routeMiddlewarevariable and add the alias to the route. E.g.

如果只想将其添加到特定路由,请将其添加到$routeMiddleware变量并将别名添加到路由。例如

protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    'admin' => 'App\Http\Middleware\AdminMiddleware',
];

You can then add it to a route, as a filter, e.g.

然后您可以将其添加到路由中,作为过滤器,例如

Route::get('admin/profile', ['middleware' => 'admin', function()
{

}]);

For additional info visit the docs:

有关其他信息,请访问文档:

http://laravel.com/docs/master/middleware

http://laravel.com/docs/master/middleware

EDIT

编辑

An improvement on this would be to use variadic functions which was introduced in PHP 5.6

对此的改进是使用 PHP 5.6 中引入的可变参数函数

http://php.net/manual/en/migration56.new-features.php

http://php.net/manual/en/migration56.new-features.php

Instead of having to make a middleware for each permission set you can do the following

您可以执行以下操作,而不必为每个权限集制作中间件

PermissionMiddleware

权限中间件

namespace App\Http\Middleware;

use Closure;
use \App\Models\Role;
class PermissionMiddleware
{
    // Pass parameters to this middleware
    public function handle($request, Closure $next, ...$permitted_roles)
    {

        //Get a users role
        $role = new Role;
        $role_name = $role->getUserRoleByName();
        foreach($permitted_roles as $permitted_role) {
            if($permitted_role == $role_name) {
                return $next($request);
            }
        }
        return redirect()->back()->withErrors('You do not have the required permission');

    }
}

Notice the ...$permitted_roles

注意 ...$permitted_roles

Route::get('admin/profile', ['middleware' => 'PermissionMiddleware:Admin,Marketing', function()
{

}]);

You can now specify as many roles as required for one middleware rather than creating multiple by using middleware parameters

您现在可以根据需要为一个中间件指定多个角色,而不是使用中间件参数创建多个角色

Docs https://laravel.com/docs/5.3/middleware#middleware-parameters

文档 https://laravel.com/docs/5.3/middleware#middleware-parameters

回答by Koushik Das

Let's assume you have a column in your users table with isAdminname which has a default value of 0 (false)

假设您的 users 表isAdmin中有一个名称为默认值为 0 (false) 的列

You can give special access using middleware in laravel like you give access to logged in users using authmiddleware in laravel. Now you need to create a middleware using the command :

您可以在 laravel 中使用中间件授予特殊访问权限,就像在 laravel 中使用中间件授予登录用户访问权限auth一样。现在您需要使用以下命令创建一个中间件:

php artisan make:middleware AdminMiddleware

In your Kernel.php you need to add this line to protected $routeMiddleware

在您的 Kernel.php 中,您需要将此行添加到 protected $routeMiddleware

'admin' => \App\Http\Middleware\AdminMiddleware::class,

In your middleware folder you have the AdminMiddlewarefile. In that you need to put your logic In this case this is how it might look like depending upon you

在您的中间件文件夹中,您有该AdminMiddleware文件。因为您需要放置您的逻辑在这种情况下,这取决于您的情况

<?php

namespace App\Http\Middleware;

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

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if(Auth::user()->isAdmin == '1') // is an admin
        {
            return $next($request); // pass the admin
        }

        return redirect('/'); // not admin. redirect whereever you like

    }
}

Now in your route you have to pass the url using this middleware Here is how it might look like

现在在您的路线中,您必须使用此中间件传递 url 下面是它的样子

Route::get('/iamanadmin', ['middleware' => 'admin', function() {
    return view('iamanadmin');
}]);

回答by Jignesh Solanki

use middleware and check for admin user.

使用中间件并检查管理员用户。

Route::get('admin', ['middleware' => 'checkadmin', function()
{

}]);

now create middleware and validate admin user.

现在创建中间件并验证管理员用户。