簡體   English   中英

使用 laravel socialite 驗證用戶的問題

[英]Problem with authenticating user using laravel socialite

我正在嘗試使用 laravel socialite 使用 google 登錄,但遇到了問題。

啟動登錄的路由:

Route::get('/auth/login/google', 'AuthController@google');

控制器中發起登錄的方法:

public function google()
{
    return Socialite::driver('google')->redirect();
}

回調路徑:

 Route::get('/auth/login/google/redirect', 'AuthController@googleRedirect');

控制器中的回調方法:

public function googleRedirect()
{
    $googleUser = Socialite::driver('google')->user();
    $email = $googleUser->getEmail();
    $user = new User();
    $user = $user->firstOrCreate(['email' => $email], ['email' => $email, 'password' => 
    bcrypt(str_shuffle('abcdefgh45678')), 'email_verified' => 1]);
    Auth::login($user, true);
}

每次我嘗試在登錄后重定向用戶時,我都會收到 ERR_EMPTY_RESPONSE。

有趣的是,我可以使用 dd(Auth::user()->id) 轉儲數據並且我正在獲取用戶的 ID,但是當我嘗試使用 return redirect('/') 我將用戶重定向到主頁時我收到空響應錯誤,如果我手動轉到主頁,我的用戶未經過身份驗證。

@Matej Petric 打擊代碼對我有用。

    public function handleProviderCallback($provider) {

        $user = Socialite::driver('google')->stateless()->user();
        $authUser = $this->findOrCreateUser($user);
        if ($authUser) {
            Auth::login($authUser, true);
            return redirect('/');
        } else {
            return redirect('/login')->withErrors(['msg', 'The Message']);
        }
    }

    public function findOrCreateUser($user) {
        $authUser = User::where('email', $user->email)->first();
        if ($authUser) {
            return $authUser;
        }
        $userN = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'password' => bcrypt(generateRandom()),
        ]);
        return $userN;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM