iT邦幫忙

2023 iThome 鐵人賽

DAY 29
0

這天: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)
    {
        //
    }

看起來好像有點笨的探討...至少把自己搞錯的觀念解清楚了!


上一篇
Laravel筆記:Validation-Day27
下一篇
Laravel:CSRF的防範機制-Day29
系列文
前輩說Laravel不難,好啊那就1人前後端試試看啊31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言