Laravel:如何将Gates与多个Guards一起使用 [英] Laravel: How to use Gates with multiple Guards
问题描述
我有一个传统的 Web 应用程序,它有许多不同的用户类型,每个用户类型都有自己的身份验证保护.
I have a traditional web application that has a number of different user types, and each user type has its own Authentication guard.
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
'timekeeper' => [
'driver' => 'session',
'provider' => 'timekeeper',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
我的大多数用户都使用网络"防护进行身份验证,但是管理员和计时员各自使用自己的防护,该防护附加到适当的用户提供程序上.
Most my users authenticate using the 'web' guard, however administrators and timekeepers each use their own guard, which is attached to an appropriate user provider.
这很好,直到我尝试使用身份验证门.如果我根据系统的默认防护措施(例如'web')对用户进行身份验证,则门将按预期工作.但是,如果我针对任何其他防护措施进行身份验证,则所有 Gate :: allows(...)
调用都将被拒绝.
This is fine until I try to use authentication gates. If I authenticate a user against the system's default guard (e.g. 'web'), then the gates work as expected. If I authenticate against any other guard however, then all Gate::allows(...)
calls are DENIED.
即使以下能力也被拒绝:
Even the following ability is denied:
Gate::define('read', function ($user) {
return true;
});
大概是由于Illuminate \ Auth \ Access \ Gate中的第284-286行:
Presumably this is due to line 284-286 in Illuminate\Auth\Access\Gate:
if (! $user = $this->resolveUser()) {
return false;
}
据我所知,我的选择是:
As far as I can see, my options are to:
- 回到使用单个网络"保护程序的情况下,用户提供程序可以定位任何类型的用户(但是我不确定如果我开始并行使用API会如何工作)
- 以某种方式在运行时设置默认防护,具体取决于当前用户的类型.(当前已在配置文件中设置)
- 以某种方式将另一个用户解析器注入Gate门面(同样取决于当前用户的类型)
但是,这些似乎都不是直观的.我想念什么吗?
None of these seems intuitive however. Am I missing something?
推荐答案
这不是最优雅的解决方案,因为它需要大量额外的样板代码,但是您可以使用 Gate :: forUser($ user)-> allows()
而不只是 Gate :: allows()
,其中 $ user
来自 Auth :: guard()
.
It's not the most elegant solution because it requires a lot of extra boilerplate code, but you can use Gate::forUser($user)->allows()
instead of just Gate::allows()
where $user
comes from Auth::guard()
.
这篇关于Laravel:如何将Gates与多个Guards一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!