我正在尝试使用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('/' )我收到的响应错误为空,如果我手动转到主页,则我的用户未通过身份验证。
答案 0 :(得分:1)
@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;
}