【问题标题】:Laravel 5 RESTful API - Understanding resource conceptsLaravel 5 RESTful API - 理解资源概念
【发布时间】:2015-10-23 17:35:48
【问题描述】:

我正在使用 Laravel 5 开发一个 RESTful API。我的 routes.php 文件中有一些资源,并且一切正常。

但现在我添加了auth.basic 中间件,我想介绍用户角色,但我很困惑。

在我的控制器中,我有一个构造函数来调用 2 个中间件,auth.basic 和角色中间件,但由于缺乏知识而无法继续。

我需要什么?好吧,我需要设置可以访问每个控制器的用户角色,但无法做到这一点。我是Controller 我想访问用户查看他的角色并与Controller上设置的角色进行比较,但是我不知道如何访问用户,您能帮帮我吗?

编辑:

我把这个放在Controller的构造函数上

public function __construct(Request $request)
  {
    $actions = $request->route()->setAction( ['roles' => ['admin', 'seller', 'buyer']]);
    $this->middleware('auth.basic');
    $this->middleware('roles');
  }

基本上,我在控制器构造函数中注入请求,然后设置一个名为角色的操作。 然后我调用中间件 auth.basic 来设置用户。 最后调用中间件角色,根据请求中的角色数组检查用户角色,如果它具有角色或者他是 root,则结果为真,否则我返回错误:

return response([
             'error' => [
             'code' => 'INSUFFICIENT_ROLE',
             'description' => 'You are not authorized to access this resource.'
         ]
         ], 401);

现在我总是遇到错误:

{"error":{"code":"INSUFFICIENT_ROLE","description":"You are not authorized to access this resource."}}

那是因为用户模型不返回角色。看我的课:

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['username', 'email', 'password', 'role_id'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    //Comprobacion del rol del usuario
    public function hasRole($roles)
    {
        $this->have_role = $this->getUserRole();
        // Check if the user is a root account
        if($this->have_role->name == 'root') {
            return true;
        }
        if(is_array($roles)){
            foreach($roles as $need_role){
                if($this->checkIfUserHasRole($need_role)) {
                    return true;
                }
            }
        } else{
            return $this->checkIfUserHasRole($roles);
        }
        return false;
    }
    private function getUserRole()
    {
        return $this->role()->getResults();
    }
    private function checkIfUserHasRole($need_role)
    {
        return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
    }

    //User relation with role

    public function role(){
      return $this->belongsTo('App\Role');
    }
}

怎么了?

【问题讨论】:

    标签: php rest laravel-5 restful-authentication middleware


    【解决方案1】:

    根据您的问题,我得到以下信息:

    如何处理身份验证中间件...

    好吧,假设你有两个中间件auth.basicauth.admin

    然后你可以让你的路线像:

    Route::post('/api/getResponse', ['middleware' => 'auth', function () {
        $var = "you have access to this route";
        return json_encode($var);
    }]);
    

    在这里,您可以设置是否以及谁可以访问此特定路由,在这种情况下,只有具有管理员权限的人才能访问它。

    例如,如果您没有“admin”的中间件,您可以通过运行工匠命令 php artisan make:middleware admin 创建它,然后将您的逻辑放入已创建的文件中。在这种情况下,逻辑将检查用户(已登录)是否具有管理员权限。

    编辑:

    正如您在回复中指出的那样:

    我不使用 Route::post,我使用 Route::resource 来处理 RESTful API 请求

    因此您可以使用组,请参阅:

    Route::group(['middleware' => 'admin'], function () {
        Route::resource('API_USER', 'API_USER_CONTROLLER');
    });
    

    这将允许您将您的管理员组用作 GROUP,因此,您所有有权访问的路由都可以进入这里。过去,我刚刚为我的所有用户组创建了单独的组,即admin 拥有自己的组,user 拥有自己的组,moderator 拥有自己的组。但是,我相信您可以使用以下内容:

    Route::group(['before' => 'auth|admin'], function()
    {
    
    } 
    

    这个组写着:should be open to auth users OR admin 但我还没有完全测试过。

    【讨论】:

    • 您的回答很有启发性,谢谢。但问题是我有超过 1 个用户角色(不仅是管理员,还有买家和卖家),而且我不使用 Route::post,我使用 Route::resource 来处理 RESTful API 请求。
    • 嗯,我想我开始明白如何去做了。刚刚开始。使用 route:group(['before]) 我假设您正在调用 auth 中间件和 admin 中间件,对吗?该|角色充当管道?我的意思是,检查身份验证,然后检查管理员?
    • @ProgramadorAdagal 是的,这是真的。或者,似乎是。老实说,我个人没有使用过这种方法来使用 pip,但我以前遇到过。方法有效吗?
    • 我无法让它工作。但我有一个想法,请查看我的编辑。
    【解决方案2】:

    找到了解决办法!!!!!!感谢 Phorce 指导我,你给了我基本的想法。我把它贴在这里给所有需要的人。如何使用 Laravel 5 为 RESTful API 获取角色身份验证。

    解释。在路由的控制器中,我调用中间件的构造函数,首先使用注入的 $request 对象添加属性角色(设置哪些角色可以访问此路由)。然后我调用中间件 auth.basic 来请求用户,然后调用另一个中间件来检查角色。安藤就是这样!一切正常。

    中间件:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class CheckRole
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            //return $next($request);
    
            // 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.
             //print "HasRole:".$request->user()->hasRole($roles).".";
             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();
             //print "actinos:".print_r($actions);
             return isset($actions['roles']) ? $actions['roles'] : null;
         }
    }
    

    用户模型

    class User extends Model implements AuthenticatableContract,
                                        AuthorizableContract,
                                        CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;
    
        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'users';
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = ['username', 'email', 'password', 'role_id'];
    
        /**
         * The attributes excluded from the model's JSON form.
         *
         * @var array
         */
        protected $hidden = ['password', 'remember_token'];
    
        protected $have_role;
        protected $profile;
    
        //Comprobacion del rol del usuario
        public function hasRole($roles)
        {
            $this->have_role = $this->getUserRole();
          //$this->have_role = $this->role()->getResults();
            // Check if the user is a root account
            if($this->have_role->nombre == 'root') {
                return true;
            }
            if(is_array($roles)){
    
                foreach($roles as $need_role){
                    if($this->checkIfUserHasRole($need_role)) {
                        return true;
                    }
                }
            } else{
                return $this->checkIfUserHasRole($roles);
            }
            return false;
        }
        private function getUserRole()
        {
            return $this->role()->getResults();
        }
        private function checkIfUserHasRole($need_role)
        {
          if($need_role === $this->have_role->nombre){
            return true;
          }else{
            return false;
          }
            //return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
        }
    
        //Relaciones de user
    
        public function role(){
          return $this->belongsTo('App\Role');
        }
    }
    

    路线:

    Route::resource('perfiles','PerfilesUsuariocontroller',[ 'only'=>['index','show'] ]);
    

    控制器构造方法

    public function __construct(Request $request)
      {
        $actions = $request->route()->setAction( ['roles' => ['root', 'admin', 'seller']]);
    
        $this->middleware('auth.basic');
        $this->middleware('roles');
      }
    

    【讨论】:

    • 很高兴您找到了解决方案 - 很抱歉我在工作中无法正确回答,无法发帖。
    • 别担心@Phorce,你给了我很多指导。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多