用户授权

更新时间: 2019-08-01 16:47

简介

除了内置的 用户认证 服务之外, Lumen 还提供了用户授权和资源访问控制的方案。有很多种方法与辅助函数能帮你处理授权逻辑。

总的来说,Lumen 中的使用和 Laravel 大同小异,我们会在这个文档中指出不同的地方,完整的用户授权文档还需要查阅 Laravel 文档

与 Laravel 的差异

定义权限

与 Laravel 相比,Lumen 的用户授权的不同之处在于如何定义权限。在 Lumen 中,你可以很方便的在你的 AuthServiceProvider 文件中使用 Gate facade 来定义你的权限:

Gate::define('update-post', function ($user, $post) {
    return $user->id === $post->user_id;
});

定义授权策略

和 Laravel 不一样的是,Lumen 的 AuthServiceProvider 中没有 $policies 数组。但是你可以在 AuthServiceProviderboot 方法里使用 Gate facade 来调用 policy 方法:

Gate::policy(Post::class, PostPolicy::class);

更多关于授权策略的信息,请参阅 Laravel 文档

检查权限

你可以像 Laravel 一样使用 Gate facade 来检查权限,首先你要确保你的 bootstrap/app.php 文件开启了 facade。 值得一提的是我们不需要将 User 实例传递给 allows 方法,认证过的用户会自动传参到用户授权的回调中:

if (Gate::allows('update-post', $post)) {
    //
}

if (Gate::denies('update-post', $post)) {
    abort(403);
}

当然你也可以传递 User 实例来检查他的权限:

if ($request->user()->can('update-post', $post)) {
    // 用户拥有更新内容的权限...
}

if ($request->user()->cannot('update-post', $post)) {
    abort(403);
}

查看更多 Laravel 中文文档 信息

PHP for the World Wide Web, Second Edition (Visual QuickStart Gu

PHP for the World Wide Web, Second Edition (Visual QuickStart Gu

Larry Ullman / Peachpit Press / 2004-02-02 / USD 29.99

So you know HTML, even JavaScript, but the idea of learning an actual programming language like PHP terrifies you? Well, stop quaking and get going with this easy task-based guide! Aimed at beginning ......一起来看看 《PHP for the World Wide Web, Second Edition (Visual QuickStart Gu》 这本书的介绍吧!

XML 在线格式化

XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具

HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具

HEX HSV 转换工具

HEX HSV 互换工具