我对Laravel身份验证中间件有一些问题。因为我希望这个中间件每次都能运行,所以我创建了新的中间件,并将其添加到API中的$middlewareGroups
中。我的中间件是这样的:
if ($request->path() === 'api/auth/signin' OR 'api/canLogin' OR 'api/check') {
return $next($request);
}
elseif (!Auth::check()){
return response()->json(['response' => false, 'status' => 403, 'message' => 'Not Authenticated'], 403);
}
奇怪的是,第一次真的奏效了(我不知道怎么回事(,但现在不行了。它总是将我重定向到public.html(因为我没有登录视图(。
我知道简单的方法是将中间件添加到每个受保护的路由中,但我希望它每次都能运行。我的路由无论如何都使用身份验证中间件(就像Route::group(['middleware' => ['auth:api']]
一样(,如果我删除这个中间件,它会给我相同的index.html
OR不能那样工作。您的IF将始终返回TRUE,因为它是一个非空字符串。它将导致if (($request->path() === "string") OR (true) OR (true))
相反,您可以使用in_array($request->path(), ["path1", "path2", "etc"])
不要使用中间件超时默认未经身份验证的异常
在Exceptions/Handler.php
中添加这行
use IlluminateAuthAuthenticationException;
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response()->json(['response' => false, 'status' => 403, 'message' => 'Not Authenticated'], 403)
: redirect('/login');
}
这是处理的更好方法