這天:Laravel authentication 文件閱讀/w Breeze-Day25
文章收尾在,發現app>Http>Middleware>Authenticate.php
裡面redirect的邏輯很不合理,
跟expectsJson有何關係?
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
其實我們拿掉這個判斷式,只回傳return route('login');
,嘗試在不登錄的狀況下,也可以用。
因為他根本跟auth的邏輯無關,只是基本檢查是不是ajax & 是不是要回傳json。
這邊可以看expectsJson的詳細解說:
https://github.com/laravel/passport/issues/100#issuecomment-248917207
我們看到的app>Http>Middleware>Authenticate.php
只是複寫了redirectTo 函式,真正的函式和auth邏輯,是在Laravel裡面,可以在vendor>laravel>framework>src>Illuminate>Auth>Middleware>Authenticate.php
裡面看到(反正就是Laravel內建的功能包啦!)
這一串邏輯會先啟動:handle function->authenticate function->沒有登錄的user就會呼叫unauthenticated->redirect
而我們會看到Redirect是空白的,我們在app>Http>Middleware>Authenticate.php
寫的邏輯就會複寫上去啦!
public function handle($request, Closure $next, ...$guards)
{
$this->authenticate($request, $guards);
return $next($request);
}
/**
* Determine if the user is logged in to any of the given guards.
*
* @param \Illuminate\Http\Request $request
* @param array $guards
* @return void
*
* @throws \Illuminate\Auth\AuthenticationException
*/
protected function authenticate($request, array $guards)
{
if (empty($guards)) {
$guards = [null];
}
foreach ($guards as $guard) {
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
}
$this->unauthenticated($request, $guards);
}
/**
* Handle an unauthenticated user.
*
* @param \Illuminate\Http\Request $request
* @param array $guards
* @return void
*
* @throws \Illuminate\Auth\AuthenticationException
*/
protected function unauthenticated($request, array $guards)
{
throw new AuthenticationException(
'Unauthenticated.', $guards, $this->redirectTo($request)
);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo(Request $request)
{
//
}
看起來好像有點笨的探討...至少把自己搞錯的觀念解清楚了!