Search code examples
laraveloauth-2.0google-apilaravel-5.5laravel-socialite

How to get user data from google using socialite google driver


I m trying to work with laravel google socialite driver where i need to get user data from google using access token that i am getting from my api call. But when i thought i have done everything correctly it's giving an error saying Call to protected method Laravel\\Socialite\\Two\\GoogleProvider::getUserByToken()

I understand that its saying i can't access that method because its protect. So how to get around this problem.

My objective

My objective is to validate the social access (basically google) token that i am getting from my mobile app and store that user's data for that particulate user into my database that i am receiving from socialite My Route in api.php

Route::post('login','api\unAuthApiCall@index');

My controller

namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Laravel\Socialite\Facades\Socialite;


class unAuthApiCall extends Controller
{
    //Get the authentication token
    public function index(Request $request){

        //get the auth token
        $authToken= Input::get('auth_token');

        //Validate authtoken with google and get user's data
        $driver = Socialite::driver('google');

        $socialUserObject= $driver->getUserByToken($authToken);

        return json_encode($socialUserObject);
    }
}

Response i am getting

{
    "message": "Call to protected method Laravel\\Socialite\\Two\\GoogleProvider::getUserByToken() from context 'App\\Http\\Controllers\\api\\unAuthApiCall'",
    "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
    "file": "C:\\Users\\CODED\\Documents\\laravelSocilte\\app\\Http\\Controllers\\api\\unAuthApiCall.php",
    "line": 28,
    "trace": [
        {
            "function": "index",
            "class": "App\\Http\\Controllers\\api\\unAuthApiCall",
            "type": "->"
        }

Solution

  • After bit of long research, and checking codes here and there. I found out the fix. It was not that complicated, apparently i found out that i was using wrong method. Here is the correct code

    $token =Input::get('auth');
    $provider='google';
    $driver= Socialite::driver($provider);
    $socialUserObject = $driver->userFromToken($token);
    print_r('$socialUserObject');
    

    This will give the complete user object.