我在我的项目中使用 Laravel Socialite 进行谷歌登录。
public function handleProviderCallback(): RedirectResponse
{
$provider = Socialite::driver('google')->scopes(['openid', 'email']);
$provider->redirectUrl(URL('oauth/google/callback'));
$oAuthUser = $provider->stateless()->user();
上述方法在大多数情况下都可以正常工作,但偶尔我会遇到错误
客户端错误:
POST https://www.googleapis.com/oauth2/v4/token
导致400 Bad Request
响应:{“error”:“invalid_request”,“error_description”:“缺少必需的参数:代码”}
我无法在本地重现此内容。请我弄清楚如何解决这个问题?
->scopes(['openid', 'email'])
后来添加来修复此问题,但未能修复。
出现此问题的原因可能有多种。潜在原因包括:
尝试修改代码并添加日志消息以获取有关该过程的更多信息:
public function handleProviderCallback(): RedirectResponse
{
try {
Log::info('Starting Google OAuth process');
$provider = Socialite::driver('google')->scopes(['openid', 'email']);
$provider->redirectUrl(URL('oauth/google/callback'));
$oAuthUser = $provider->stateless()->user();
Log::info('Received callback from Google', ['user' => $oAuthUser]);
// Your existing code to handle the user
} catch (\Exception $e) {
Log::error('Error during Google OAuth process', ['error' => $e->getMessage()]);
return redirect('/login')->withErrors('Google login failed, please try again.');
}
}
此外,检查存储会话的配置是否正确(https://laravel.com/docs/11.x/session)。