用于 API 的 Laravel 中间件身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34921430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Middleware Auth for API
提问by rosscooper
I am currently developing and application that has an API which I want to be accessible through middleware that will check if the user is authenticated using either Laravel's default Auth middleware and Tymone's JWT.Auth token based middleware so requests can be authenticated either of the ways.
我目前正在开发一个具有 API 的应用程序,我希望可以通过中间件访问该 API,该 API 将检查用户是否使用 Laravel 的默认 Auth 中间件和 Tymone 的基于 JWT.Auth 令牌的中间件进行身份验证,以便请求可以通过任何一种方式进行身份验证。
I can work out how to have one or the other but not both, how could I do this? I'm thinking I need to create a custom middleware that uses these existing middlewares?
我可以弄清楚如何拥有一个或另一个但不能同时拥有,我怎么能做到这一点?我想我需要创建一个使用这些现有中间件的自定义中间件?
I am using Laravel 5.1
我正在使用 Laravel 5.1
Thanks
谢谢
回答by rosscooper
Turns out I did need to make my own middleware which was easier than I thought:
事实证明,我确实需要制作自己的中间件,这比我想象的要容易:
<?php
namespace App\Http\Middleware;
use Auth;
use JWTAuth;
use Closure;
class APIMiddleware {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
try {
$jwt = JWTAuth::parseToken()->authenticate();
} catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
$jwt = false;
}
if (Auth::check() || $jwt) {
return $next($request);
} else {
return response('Unauthorized.', 401);
}
}
}
Then I use this middleware on my api route group like so after registering in the kernel:
然后我在内核中注册后在我的 api 路由组上使用这个中间件:
Route::group(['prefix' => 'api', 'middleware' => ['api.auth']], function() {
回答by Dippner
I think you can use Route::group
in your routes.php file and define the middlewares you want to use in an array.
我认为您可以Route::group
在 routes.php 文件中使用并定义要在数组中使用的中间件。
Route::group(['middleware' => ['auth', 'someOtherMiddleware']], function()
{
Route::get('api/somethinglist', function(){
return App\Something::all();
});
});
If I'm not mistaken all routes defined within that route group is checked against the middleware(s) you specify in the array.
如果我没有记错的话,会根据您在数组中指定的中间件检查该路由组中定义的所有路由。