我希望可以使用标准auth:api
中间件或CheckClientCredentials
中间件访问一组路由。
我无法看到这是如何实现的,因为没有能力将中间件设置为只需要一个列出的中间件。
是否有Passport中间件允许我不知道的任何类型的API身份验证?
或者是否有一种干净的方法来创建自定义中间件来测试任何一个中间件?
答案 0 :(得分:0)
Laravel不提供 OR 中间件。虽然有几种解决方法,就像之前被问过here一样。
如果您正在寻找更改api.php
默认中间件(默认为auth:api
)的方法,您可以在目录中看到它:app\Providers\RouteServiceProvider.php
,其功能名称为:{{1} }。
答案 1 :(得分:0)
我接受了Joshuas关于的建议,并创建了一个包含两个auth中间件的新中间件。
为下面遇到此问题的其他人工作中间件课程。这将首先尝试Auth guard中间件,如果无法验证请求,它将尝试使用Client Credentials Passport中间件进行身份验证。
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as AuthGuardMiddleware;
use Laravel\Passport\Http\Middleware\CheckClientCredentials as ClientCredMiddleware;
class AuthenticateWithApiOrClientCreds
{
/**
* Authenticate a request with either Authenticate OR CheckClientCredentials Middleware
*
* @param $request
* @param Closure $next
* @param mixed ...$scopes
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function handle($request, Closure $next, ...$scopes)
{
$auth_guard_middleware = app()->make(AuthGuardMiddleware::class);
try {
$response = $auth_guard_middleware->handle($request, $next, 'api');
} catch (AuthenticationException $e) {
$client_cred_middleware = app()->make(ClientCredMiddleware::class);
$response = $client_cred_middleware->handle($request, $next, ...$scopes);
}
return $response;
}
}
答案 2 :(得分:0)
我最终将所有需要身份验证的路由存储在名为tandc : false
的单独路由文件中。在RouteServiceProvider.php中,我根据授权标头的存在条件有条件地为这些路由应用api-authenticated.php
和web
中间件组。设置了Authorization标头后,您就知道该用户是API客户端。
在api
中:
Providers/RouteServiceProvider.php