Laravel socialite - Google auth works locally but not in production: Missing required parameters code
Asked Answered
U

5

6

I have a problem in my production environment with Laravel Socialite's Google auth. The error is same as on this post:

laravel socialite not working on live server, only works on local machine

but I have an Apache server and after many tries, I haven't found a solution.

Edit:

Client error: POST "https://www.googleapis.com/oauth2/v4/token" resulted in a "400 Bad Request" response:

{
 "error": "invalid_request",
 "error_description": "Missing required parameter: code"
}
Uneven answered 25/11, 2019 at 12:5 Comment(6)
what kind of error do you receive?Mani
Yes, sorry, the same in the link, i receive that :"Client error: POST https://www.googleapis.com/oauth2/v4/token resulted in a 400 Bad Request response:↵{↵ "error": "invalid_request",↵ "error_description": "Missing required parameter: code"↵}↵Uneven
Does this answer your question? Laravel socialite 400 Bad Request responseCeltic
thx but not is not the same problemUneven
is it working when running php artisan serve?Mani
Its work on local with Mamp, same with php artisan serveUneven
M
1
    public function redirectToProvider($driver)
{
  //  return Socialite::driver($driver)->stateless()->redirect();
    return Socialite::driver('google') ->setScopes(['openid', 'email'])

        ->redirect();
}
Mahala answered 28/1, 2021 at 9:15 Comment(2)
While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.Geraldine
if I add third parameter to scope it return error to me. can you plz tell how to get name using scope..? setScopes(['openid', 'email', 'name'])Soberminded
O
0

See this answer if you are running an Nginx server.

Run sudo nano /etc/nginx/sites-available/default or your site config file

and fixed this line:

try_files $uri $uri/ /index.php?query_string; // wrong

to

try_files $uri $uri/ /index.php?$query_string; // fixed

Outrank answered 9/1, 2023 at 19:31 Comment(0)
A
0

check first your redirect url is correct and run command:

php artisan passport:install

see this below snippet may help you

 public function socialRedirect($provider)
  {
    if ($provider === 'clever') {
      $clientId = Config::get('services.clever.client_id');
      $redirect = Config::get('services.clever.redirect');
      return redirect()->away('https://clever.com/oauth/authorize?response_type=code&redirect_uri=' . $redirect . '&client_id=' . $clientId);
    } else {
      return Socialite::driver($provider)->redirect();
    }
  }

  public function socialCallback($provider)
  {
    if ($provider === 'apple') {
      $token = app(Configuration::class)->parser()->parse(app(AppleToken::class)->generate());
      config()->set('services.apple.client_secret', $token);
    }

    $socialUser = Socialite::driver($provider)->setHttpClient(new Client(['verify' => false]))->user();

    $userIdentity = UserIdentity::where('provider_id', $socialUser->id)->where('provider_name', $provider)->first();
    $userRole = UserRole::where('slug', 'user')->first();

    if ($userIdentity) {
      // retrieve the user from users store
      $user = User::where('id', $userIdentity->user_id)->with('userRole')->with('account')->first();

      // assign access token to user
      $token = $user->createToken('social');
      $accessToken = $token->accessToken;

      $arguments = [
        'success' => true,
        'accessToken' => $accessToken,
        'expiresAt' => Carbon::parse($token->token->expires_at)->toDateTimeString(),
        'user' => json_encode($user)
      ];

      return redirect()->away(env('CLIENT_URL') . '/social/callback?' . http_build_query($arguments));
    } else {
      $user = User::where('email', $socialUser->email)->with('userRole')->with('account')->first();

      if (!($user && isset($user->id))) {
        /* $newUser = User::create([
          'fname' => $socialUser->name ?? '',
          'lname' => '',
          'email' => $socialUser->email,
          'image' => $socialUser->avatar ?? '',
          'user_role_id' => $userRole->id,
          'account_id' => 1,
          'password' => Hash::make(Str::random(40)),
          'status' => 'active',
        ]);

        $user = User::where('email', $socialUser->email)->with('userRole')->with('account')->first(); */

        $arguments = [
          'success' => false,
        ];

        return redirect()->away(env('CLIENT_URL') . '/social/callback?' . http_build_query($arguments));
      } else {
        // store user social provider info
        if ($user) {
          UserIdentity::create([
            'provider_name' => $provider,
            'provider_id' => $socialUser->id,
            'user_id' => $user->id,
          ]);
        }

        // assign passport token to user
        $token = $user->createToken('social');
        $accessToken = $token->accessToken;

        $arguments = [
          'success' => true,
          'accessToken' => $accessToken,
          'expiresAt' => Carbon::parse($token->token->expires_at)->toDateTimeString(),
          'user' => json_encode($user)
        ];

        return redirect()->away(env('CLIENT_URL') . '/social/callback?' . http_build_query($arguments));
      }
    }
Analyse answered 22/2, 2023 at 12:34 Comment(0)
I
0

Before I knew the problem, my code was like this.

$user = Socialite::driver($provider)->stateless()->user();
$existingUser = User::where('email', $user->email)->first();

On my history error happened in method user() after stateless() the problem happens when user clicks the button cancel in sign in to process on page login with Google. As we know, after you choose your email will redirect you to a new page with option Cancel | Continue

So we apply try catch like this

try {
  $user = Socialite::driver($provider)->stateless()->user();
} catch (\Exception $e) {
  return redirect()->to('https://blablabla.id/login');
}

And it solved.

Introject answered 12/10 at 6:20 Comment(0)
A
-2

This issue occurred due to profile scope in vendor\laravel\socialite\src\Two\GoogleProvider.php .

You can overcome this error by following 2 ways:

  1. Remove OR comment profile scope in vendor\laravel\socialite\src\Two\GoogleProvider.php
    protected $scopes = [
        'openid',
        'email',
    ];
  1. Initiate the Google OAUth2 stateless();
    return Socialite::driver('google')->stateless()->redirect();
Artemus answered 1/9, 2020 at 21:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.