【问题标题】:Laravel/Lumen: How to authorize Controller access?Laravel/Lumen:如何授权控制器访问?
【发布时间】:2018-04-12 22:07:05
【问题描述】:

这是我的第一个 Laravel/Lumen 项目,因此我的知识还不是最好的。

我的路线:

$router->group(['prefix' => 'rest/v1','middleware' => 'auth'], function($router) {
    $router->get('articles','ArticleController@index');

    $router->get('article/{id}','ArticleController@getarticle');
});

我的控制器:

class ArticleController extends Controller{
    public function index(){
        if(!CapabilityService::currentUserCan('fetch_basic_content')) {
            return response('Insufficient permissions.', 401);
        }
        return response()->json(Article::all());
    }

    public function getArticle($id){
        if(!CapabilityService::currentUserCan('fetch_basic_content')) {
            return response('Insufficient permissions.', 401);
        }
        return response()->json(Article::find($id));
    }
}

这当然很麻烦,尤其是因为它是访问我的控制器中所有功能的相同权限。但是我必须使用我的自定义CapabilityService 来检查权限。我怎样才能更好地实现这一点?

【问题讨论】:

  • 创建一个policy怎么样
  • 策略也适用于控制器吗?
  • 是的,你可以使用这样的控制器助手$this->authorize('update', $post);

标签: php laravel authorization lumen


【解决方案1】:

您可以通过创建一个新的中间件来做到这一点。

$router->group(['prefix' => 'rest/v1','middleware' => ['auth','your-custom-middleware']], function($router) {
    $router->get('articles','ArticleController@index');

    $router->get('article/{id}','ArticleController@getarticle');
});

现在在您的中间件 handle 方法中执行类似的操作

if(!CapabilityService::currentUserCan('fetch_basic_content')) {
            return response('Insufficient permissions.', 401);
        }
return $next($request);

【讨论】:

  • 一个有趣的方法来解决它没有政策或门,谢谢。
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多