Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Neeraj1005's avatar

Login with google using socialite not working in production

In my application I made a social login using socialite pkg. The problem I'm facing is that. Login with google is perfectly working in my local enviroment but in production it is not working and redirect back to PageNotFound page. Can anyone helps me how to solve this problem. This is my service which I've defined

    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => 'https://digitalcrm.com/crm/auth/google/callback',
    ],

This is my route

Auth::routes();

Route::get('/auth/google/redirect', 'Socialite\SocialiteController@google')->name('google.login');
Route::get('/auth/google/callback', 'Socialite\SocialiteController@googleRedirect');

This is my controller

<?php

namespace App\Http\Controllers\Socialite;

use App\User;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Facades\Socialite;

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

    public function googleRedirect()
    {
        try {
            $user = Socialite::driver('google')->user();
            $user = User::firstOrCreate([
                'email' =>$user->getEmail()
            ],[
                'name' => $user->getName(),
                'password' => Hash::make(Str::random(24))
            ]);
            Auth::login($user, true);
            return redirect('/dashboard');
        } catch (\Throwable $th) {
            return redirect('/login')->withError('Something went wrong! '.$th->getMessage());
        }
    }
}

Note: I registered the url in google console.

0 likes
30 replies
Neeraj1005's avatar

@silencebringer I tried this one, not working same page not found occurs

'redirect' => 'https://digitalcrm.com/auth/google/callback',
SilenceBringer's avatar

@neeraj1005 try to visit https://digitalcrm.com/auth/google/callback in browser. You'll see your own page not found error. It means you have something which catch this route and tried to parse another way.

Try to move both routes

Route::get('/auth/google/redirect', 'Socialite\SocialiteController@google')->name('google.login');
Route::get('/auth/google/callback', 'Socialite\SocialiteController@googleRedirect');

to the very top of your route file

Neeraj1005's avatar

I did, put the url in top and it is not working again. 🥺

Neeraj1005's avatar

@silencebringer THis is the url

+--------+----------+----------------------+--------------+-------------------------------------------------------------------+------------+
| Domain | Method   | URI                  | Name         | Action                                                            | Middleware |
+--------+----------+----------------------+--------------+-------------------------------------------------------------------+------------+
|        | GET|HEAD | auth/google/callback |              | App\Http\Controllers\Socialite\SocialiteController@googleRedirect | web |
|        | GET|HEAD | auth/google/redirect | google.login | App\Http\Controllers\Socialite\SocialiteController@google         | web |
+--------+----------+----------------------+--------------+-------------------------------------------------------------------+-----------
SilenceBringer's avatar

@neeraj1005 ok, correct url should be

'redirect' => 'https://digitalcrm.com/crm/auth/google/callback'

keep google routes at the top of routes file

And try to remove try/catch block in action to see if any error occurred

public function googleRedirect()
    {
        //try {
            $user = Socialite::driver('google')->user();
            $user = User::firstOrCreate([
                'email' =>$user->getEmail()
            ],[
                'name' => $user->getName(),
                'password' => Hash::make(Str::random(24))
            ]);
            Auth::login($user, true);
            return redirect('/dashboard');
        //} catch (\Throwable $th) {
        //    return redirect('/login')->withError('Something went wrong! '.$th->getMessage());
        //}
    }
1 like
SilenceBringer's avatar

@neeraj1005 ok.... so, try to clear all caches on the server

php artisan optimize:clear

and try again. If it will not works - let's do test callback. in routes file, at the very top

Route::get('/testcallback', function () {
    dd(Socialite::driver('google')->user());
});

and change redirect url to

'redirect' => 'https://digitalcrm.com/crm/testcallback'
Neeraj1005's avatar

@silencebringer Now getting an Error

Laravel\Socialite\Two\InvalidStateException
https://digitalcrm.com/crm/testcallback
SilenceBringer's avatar

@neeraj1005

Route::get('/testcallback', function () {
        $user = Socialite::driver('google')->stateless()->user();
    dd($user);
});
Neeraj1005's avatar

@silencebringer Now this error

GuzzleHttp\Exception\ClientException
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" }
anilkumarthakur60's avatar

@neeraj1005 google facebook require HTTPS enables server does your server have that....try with GitHub login if that github work then rest of social media login should work

Neeraj1005's avatar

Yes https enabled. Check this url digitalcrm.com/crm/login

anilkumarthakur60's avatar

.env file

GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_CLIENT_REDIRECT=http://getwellpharmacy.com/login/github/callback

route


Route::get('login/{driver}', 'Auth\LoginController@redirectToProvider')->name('social.oauth');
Route::get('login/{driver}/callback', 'Auth\LoginController@handleProviderCallback')->name('social.callback');

login.blade.php ``

@csrf
                    <div class="form-group row">
                        <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

                        <div class="col-md-6">
                            <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                            @error('email')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="form-group row">
                        <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                        <div class="col-md-6">
                            <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                            @error('password')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-md-6 offset-md-4">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                <label class="form-check-label" for="remember">
                                    {{ __('Remember Me') }}
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="form-group row mb-0">
                        <div class="col-md-8 offset-md-4">
                            <button type="submit" class="btn btn-primary">
                                {{ __('Login') }}
                            </button>
                            <a href="{{ route('social.oauth','github') }}" class="btn btn-info"> Github</a>

                            <a href="{{ route('social.oauth','facebook') }}" class="btn btn-info">facebook </a>
                            <a href="{{ route('social.oauth','twitter') }}" class="btn btn-info"> twitter</a>
                            <a href="{{ route('social.oauth','google') }}" class="btn btn-info"> google</a>


                            @if (Route::has('password.request'))
                                <a class="btn btn-link" href="{{ route('password.request') }}">
                                    {{ __('Forgot Your Password?') }}
                                </a>
                            @endif
                        </div>
                    </div>
                </form>
login controller 

protected $providers = [ 'github','facebook','google','twitter' ];

public function redirectToProvider($driver)
{
    if( ! $this->isProviderAllowed($driver) ) {
        return $this->sendFailedResponse("{$driver} is not currently supported");
    }

    try {
        return Socialite::driver($driver)->redirect();
    } catch (Exception $e) {
        // You should show something simple fail message
        return $this->sendFailedResponse($e->getMessage());
    }
}


public function handleProviderCallback( $driver )
{
    try {
        $user = Socialite::driver($driver)->user();
    } catch (Exception $e) {
        return $this->sendFailedResponse($e->getMessage());
    }

    // check for email in returned user
    return empty( $user->email )
        ? $this->sendFailedResponse("No email id returned from {$driver} provider.")
        : $this->loginOrCreateAccount($user, $driver);
}

protected function sendSuccessResponse()
{
  
     return redirect()->intended($this->redirectTo());





}

protected function sendFailedResponse($msg = null)
{
    toastr()->warning('Unable to login, try with another provider to login.');
    return redirect()->route('login')
        ->withErrors(['msg' => $msg ?: 'Unable to login, try with another provider to login.']);
}

protected function loginOrCreateAccount($providerUser, $driver)
{
    // check for already has account
    $user = User::where('email', $providerUser->getEmail())->first();

    // if user already found
    if( $user ) {
        // update the avatar and provider that might have changed
        $user->update([
            'avatar' => $providerUser->avatar,
            'provider' => $driver,
            'provider_id' => $providerUser->id,
            'access_token' => $providerUser->token,

        ]);
    } else {
        // create a new user
        $user = User::create([
            'name' => $providerUser->getName(),
            'email' => $providerUser->getEmail(),
            'avatar' => $providerUser->getAvatar(),
            'provider' => $driver,
            'provider_id' => $providerUser->getId(),
            'access_token' => $providerUser->token,
            'email_verified_at' => now(),
            // user can use reset password to create a password
            'password' => ''
        ]);
    }

    // login the user
    Auth::login($user, true);

    return $this->sendSuccessResponse();
}

private function isProviderAllowed($driver)
{
    return in_array($driver, $this->providers) && config()->has("services.{$driver}");
}


Neeraj1005's avatar

@anilkumarthakur60 I tried and used your code. Again it is working properly in localhost but i don't know why it is not working on production

Neeraj1005's avatar

@anilkumarthakur60 my APP_URL is same see this

APP_URL=https://digitalcrm.com/crm

Now I think I should try other platform twitter or more..

anilkumarthakur60's avatar

@neeraj1005 above code will work for all the Social media login.... try for github login....if that works then all social media login should work

Neeraj1005's avatar

yes, I'll try it for github and twitter as well.

Please or to participate in this conversation.