Laravel 5中的多种身份验证用户类型 [英] Multiple auth user types in Laravel 5

查看:59
本文介绍了Laravel 5中的多种身份验证用户类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将身份验证用户组分为3个组,我需要admin,client和worker组.

How can I separate auth user group into 3 groups, I need admin, client and worker group.

这是我为身份验证用户提供服务的路线:

Here is my route for auth users:

Route::group(['middleware' => 'auth'], function(){

    Route::get('home', array(
        'as' => 'home',
        'uses'  => 'HomeController@index'
        ));


    Route::get('logout', array(
       'as' => 'logout',
       'uses' => 'UserController@logout'
    ));


});

推荐答案

我已经编写了一个中间件,该中间件可以执行基于角色的基本身份验证,如您所描述的.

I've written a middleware that can do basic role based authentication, as you've described.

Route::get('home', [
     'middleware' => ['auth', 'roles'], //use the roles middleware
     'uses' => 'HomeController@index',
     'roles' => ['admin', 'client'] // only admin and client roles are allowed
]);

说明

在App \ Http \ Middleware中,创建一个名为"CheckRole.php"的文件

Instructions

In App\Http\Middleware, create a file called 'CheckRole.php'

<?php namespace App\Http\Middleware;
// First copy this file into your middleware directoy
use Closure;
class CheckRole{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
    // Get the required roles from the route
    $roles = $this->getRequiredRoleForRoute($request->route());
    // Check if a role is required for the route, and
    // if so, ensure that the user has that role.
    if($request->user()->hasRole($roles) || !$roles)
    {
        return $next($request);
    }
    return response([
        'error' => [
        'code' => 'INSUFFICIENT_ROLE',
        'description' => 'You are not authorized to access this  resource.'
    ]
    ], 401);
    }
    private function getRequiredRoleForRoute($route)
    {
        $actions = $route->getAction();
        return isset($actions['roles']) ? $actions['roles'] : null;
    }
} 

在内核中,启用角色"中间件:

In kernel, enable the 'roles' middleware:

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

您还需要建立一个角色表,其中包含一些角色数据,然后将关系分配给User模型上的角色.

You will also need to set up a roles table, with some role data and then assign the relationships to the role on the User model.

完整代码可在此处找到: https://gist.github.com/amochohan/8cb599ee5dc0af5f4246

The full code is available here: https://gist.github.com/amochohan/8cb599ee5dc0af5f4246

希望这会有所帮助.

这篇关于Laravel 5中的多种身份验证用户类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆