[英]Is it possible to use both of auth and auth:api middlewares on the same controller in Laravel?
I got the task to implement API for mobile using Laravel Passport (for OAUTH2 support). 我得到了使用Laravel Passport(用于OAUTH2支持)为移动设备实现API的任务。 I want to reuse the same Controller methods (some of them) that I use on the website.
我想重复使用网站上使用的相同Controller方法(其中一些方法)。 I have tried doing this:
我尝试这样做:
public function __construct()
{
$this->middleware('auth');
$this->middleware('auth:api');
}
But that doesn't work (why?). 但这不起作用(为什么?)。 Do I just have to create new controllers for the api?
我是否只需要为api创建新的控制器? Thanks!
谢谢!
In your routes file you can specify multiple middleware's by doing. 在路由文件中,您可以这样做指定多个中间件。
Route::middleware(['auth:api', 'auth'])->group(function() {
//my routes
});
But it seems like for your use, you could just use auth:api
in your api routes file and auth
in your web routes file. 但好像你使用,你可以只使用
auth:api
在您的API文件航线和auth
在您的网页routes文件。
Additionally if you'd like to middleware the entire controller without grouping via routes you can use middleware groups. 另外,如果您希望中间件整个控制器而不通过路由进行分组,则可以使用中间件组。
In your Http Kernel.php
add a new index to the array $middlewareGroups
在您的Http
Kernel.php
,向数组$middlewareGroups
添加新索引。
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
'auth:api',
],
'both' => [
'auth:api',
'auth'
],
];
Then in your controller you should be able to do: 然后,在您的控制器中,您应该能够执行以下操作:
public function __construct() {
$this->middleware('both');
}
Additionally you can exclude methods within the controller from the middleware group. 另外,您可以从中间件组中排除控制器内的方法。
public function __construct() {
$this->middleware('both', ['except' => [ 'methodOne', 'methodTwo' ]]);
}
If you want to have 2 different Auth guards checking for a user you can do that with the auth
middleware. 如果要让2个不同的Auth Guard来检查用户,则可以使用
auth
中间件来进行。 It takes a unspecified number of parameters: 它使用未指定数量的参数:
auth:web,api
That will check each guard for a user until one is returned then use that as the current guard for the request. 这将检查用户的每个防护,直到返回一个用户,然后将其用作请求的当前防护。
What you have are 2 different middleware being ran in the stack. 您所拥有的是在堆栈中运行的2种不同的中间件。 Since only one of them will actually pass you are always 'unauthenticated' with your setup.
由于只有其中一个会通过,因此您的设置始终“未经身份验证”。 (unless you have a session and are passing a token for some odd reason).
(除非您有一个会话并且出于某种奇怪的原因传递令牌)。
SO - Laravel two diffrent middleware authentication from auth middleware only 所以-Laravel仅来自身份验证中间件的两个不同的中间件身份验证
SO - Laravel multi auth protecting route multple middleware not working 所以-Laravel多身份验证保护路由多个中间件不起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.