介绍
除了开箱即用地提供身份验证服务外,Lumen还提供了一种简单的方法来组织授权逻辑并控制对资源的访问。有多种方法和助手可以帮助您组织授权逻辑。
通常,可以在Lumen中使用授权,就像在Laravel中使用授权一样。我们将在此处介绍一些差异,但是您应该参考Laravel完整文档以获取更多详细信息。
与Laravel的区别
定义能力
与Laravel相比,在Lumen中使用授权的主要区别在于如何定义功能。在流明中,您可以仅使用Gate
外墙AuthServiceProvider
来定义能力:
Gate::define('update-post', function ($user, $post) {
return $user->id === $post->user_id;
});
定义政策
与Laravel不同,Lumen的$policies
数组没有AuthServiceProvider
。但是,您仍然可以从提供者的方法中policy
在Gate
外观上调用该boot
方法:
Gate::policy(Post::class, PostPolicy::class);
同样,要了解有关策略的更多信息,请查阅完整的Laravel文档。
检查能力
您可以像在整个Laravel框架中一样“检查”功能。首先,您可以使用Gate
立面。如果选择使用外观,请确保在文件中启用外观。请记住,我们不需要将实例传递到方法中,因为当前已通过身份验证的用户将自动传递到您的授权回调:bootstrap/app.php``User``allows
if (Gate::allows('update-post', $post)) {
//
}
if (Gate::denies('update-post', $post)) {
abort(403);
}
当然,您也可以检查给定User
实例是否具有给定功能:
if ($request->user()->can('update-post', $post)) {
// The user is allowed to update the post...
}
if ($request->user()->cannot('update-post', $post)) {
abort(403);
}