在 Laravel 中,如果您使用自定义身份验证,如何使用 Gate?

问题描述 投票:0回答:4

我想在 Laravel 8 中使用 Gates,但我们使用的是自定义身份验证,因此 Laravel 不知道将什么 $user 记录传递到 Gate 中。那么我如何告诉 Laravel 某个用户当前已登录,以便使用正确的用户记录?

谢谢。

php laravel laravel-authentication laravel-authorization laravel-gate
4个回答
3
投票

您可以使用

forUser
方法:

Gate::forUser($user)->allows('update-post', $post);
//    ^^^^^^^^^^^^^^

检查文档的此部分


1
投票

我不知道你的验证过程是在AppServiceProvider文件中还是在控制器中完成的。

但是我认为在控制器中验证后,您可以使用该功能

Auth::setUser($user)

0
投票

所以这就是我所做的:

\App\Models
中,我创建了一个扩展了
Illuminate\Foundation\Auth\User

的User类

我还在

$table
$primaryKey
类中设置了受保护的属性来指定我的自定义表名称和主键名称。

然后在我的中间件中,我检查用户是否已登录(如果是),然后运行以下命令:

\Illuminate\Support\Facades\Auth::login(\App\Models\User::find($userId))

当我完成这一切后,我可以在任何我想要的地方使用

Auth::user()
。据推测,门现在无需每次都指定用户即可工作。


0
投票

一个老问题,但与 Laravel 8 和 Laravel 11 一样相关:

您可以将自己的用户解析方法绑定到 Gate 类,以使一切都开箱即用。

在 Laravel 的供应商中

AuthServiceProvider.php
你会看到这段代码:


    protected function registerAccessGate()
    {
        $this->app->singleton(GateContract::class, function ($app) {
            return new Gate($app, fn () => call_user_func($app['auth']->userResolver()));
        });
    }

这基本上告知了我们需要了解的有关如何解析我们自己的用户的所有信息。

在您的

app/Providers/AppServiceProvider.php
中,您可以将以下内容添加到
register
方法中:

    protected function registerAccessGate()
    {
        $this->app->singleton(GateContract::class, function ($app) {
            return new Gate($app, function() {
                // do whatever you want to resolve your user, 
                // and return it via this method
                // return User
            });
        });
    }

还值得注意的是,此示例中的

GateContract
是别名引用:


use Illuminate\Contracts\Auth\Access\Gate as GateContract;

© www.soinside.com 2019 - 2024. All rights reserved.