在路由组上设置默认防护 [英] Setting the default guard on a route group
问题描述
我已经为我的用户设置了API令牌,他们可以在访问API路由以返回其他数据时选择性地提供这些令牌.
I have set up an API token for my users which they can optionally provide when accessing API routes for additional data to be returned.
这是我的 auth.php 配置:
'defaults' => [
'guard' => 'web',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'eloquent',
],
'api' => [
'driver' => 'token',
'provider' => 'eloquent',
],
],
我的代码中有多个(共享)位置,它们使用像$request->user()
这样的检查,而没有提供保护.问题在于,它始终使用默认防护.
I have various (shared) places in my code which use checks like $request->user()
without providing the guard. The problem is that this always uses the default guard.
但是,如果我将其中一个API路由设置为使用中间件auth:api
,则默认情况下它会使用api Guard,这与我期望的一样.但是我真的不能设置它,因为如前所述,身份验证是可选的,使用auth中间件使其成为必需.
However if I set one of the API routes as to use middleware auth:api
then it uses the api guard by default as I'd expect. I can't really set that up though because as I mentioned, authentication is optional and using the auth middleware makes it mandatory.
我想知道是否有一种方法可以设置所有API路由,以使它们的默认防护为API防护.
I'm wondering if there's a way to set all API routes such that their default guard is the API guard.
推荐答案
经过一番摆弄之后,我认为我发现了我认为是明智的解决方案:
After some fiddling about I think I've found what I think is a sensible solution:
我创建了以下中间件:
class GuardSwitcher {
public function handle($request, \Closure $next, $defaultGuard = null) {
if (in_array($defaultGuard, array_keys(config("auth.guards")))) {
config(["auth.defaults.guard" => $defaultGuard]);
}
return $next($request);
}
}
然后我将其添加为路由中间件:
I then added this as a route middleware:
protected $routeMiddleware = [
// ... more
'guardswitcher' => GuardSwitcher::class
];
然后我将此中间件添加到Kernel.php
的api中间件堆栈中,即:
I then added this middleware in my api middleware stack in Kernel.php
i.e.:
'api' => [
'guardswitcher:api',
// ... more
],
此过程完成后,Kernel.php
会如下所示:
After this process this is what the Kernel.php
would look like:
class Kernel extends HttpKernel
{
protected $middleware = [
//These are the global framework middleware which were not changed
];
protected $middlewareGroups = [
'web' => [
//Web middleware, no changes here
],
'api' => [
'guardswitch:api',
// Other group middleware
]
];
protected $routeMiddleware = [
// Other middleware go here
'guardswitch' => DefaultGuardSwitch::class, // This is what's added
];
}
这篇关于在路由组上设置默认防护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!