dongzhi1822 2015-10-30 15:12
浏览 148
已采纳

在Laravel中,如果已经检查过中间件,我应该检查控制器的权限吗?

I created a middleware that checks if the user is authorized to perform an action and added this middleware to the routes that I want to protect like this:

// VerifyPermission middleware

class VerifyPermission {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param $permission
     * @return mixed
     */
    public function handle($request, Closure $next, $permission)
    {
        $user = auth()->user();

        if (auth()->check() && $user->hasPermission($permission))
        {
            return $next($request);
        }

        return redirect('/');
    }
}

// Routes

Route::patch('company/{id}', ['as' => 'updateCompany',
                              'uses' => 'SettingsController@updateCompany',
                              'middleware' => 'permission:manage_company']
);

My question is, is it necessary to make another check on updateCompany or is the middleware check sufficient?

public function updateCompany()
{
    if(Auth::user()->hasPermission('manage_company'))
    {
        // Updates Company
    }   

    return abort(403, "Unauthorized");
}
  • 写回答

1条回答 默认 最新

  • dt246813579 2015-10-30 15:20
    关注

    No, you should not make another check, the middleware will do it.

    In fact handling authentication and permission handling is one of the most frequent uses for middleware

    when you specify this:

    Route::patch('company/{id}', ['as' => 'updateCompany',
                              'uses' => 'SettingsController@updateCompany',
                              'middleware' => 'permission:manage_company']
    

    You're telling laravel that, when it finds a company/{id} route, it should trigger the handle method of the permission:manage_company middleware, before the request is sent to the SettingsController

    So, when the request will get to your controller you're sure that it has satisfied all the middleware it went through

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化