[英]Laravel/Lumen: How to authorize Controller access?
This is my first Laravel/Lumen project therefore my knowledge is not the best yet. 这是我的第一个Laravel / Lumen项目,因此我的知识还不是最好的。
My Route: 我的路线:
$router->group(['prefix' => 'rest/v1','middleware' => 'auth'], function($router) {
$router->get('articles','ArticleController@index');
$router->get('article/{id}','ArticleController@getarticle');
});
My Controller: 我的控制器:
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));
}
}
This is very cumbersome of course, especially as it is the same permission for accesssing all functions within my Controller. 当然这非常麻烦,特别是因为它具有访问Controller中所有功能的相同权限。 However I have to use my custom
CapabilityService
in order to check the permissions. 但是,我必须使用我的自定义
CapabilityService
来检查权限。 How can I implement this better? 我该如何更好地实施?
You can do that by creating a new middleware. 您可以通过创建新的中间件来实现。
$router->group(['prefix' => 'rest/v1','middleware' => ['auth','your-custom-middleware']], function($router) {
$router->get('articles','ArticleController@index');
$router->get('article/{id}','ArticleController@getarticle');
});
Now in your middleware handle
method do something like 现在在您的中间件
handle
方法中执行类似的操作
if(!CapabilityService::currentUserCan('fetch_basic_content')) {
return response('Insufficient permissions.', 401);
}
return $next($request);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.