authenticationgoogle-apioauth-2.0

How to identify a Google OAuth2 user?


I used Facebook login to identify users. When a new user comes, I store their userID in my database. Next time they come, I recognized their Facebook ID and I know which user it is in my database.

Now I am trying to do the same with Google's OAuth2, but how can I recognize the users?

Google sends me several codes and tokens (access_token, id_token, refresh_token), however none of them are constant. Meaning if I log out and log back in 2 minutes later, all 3 values have changed. How can I uniquely identify the user?

I am using their PHP client library: https://code.google.com/p/google-api-php-client/


Solution

  • I inserted this method into google-api-php-client/src/apiClient.php:

    public function getUserInfo() 
    {
        $req = new apiHttpRequest('https://www.googleapis.com/oauth2/v1/userinfo');
        // XXX error handling missing, this is just a rough draft
        $req = $this->auth->sign($req);
        $resp = $this->io->makeRequest($req)->getResponseBody();
        return json_decode($resp, 1);  
    }
    

    Now I can call:

    $client->setAccessToken($_SESSION[ 'token' ]);
    $userinfo = $client->getUserInfo();
    

    It returns an array like this (plus e-mail if that scope has been requested):

    Array
    (
        [id] => 1045636599999999999
        [name] => Tim Strehle
        [given_name] => Tim
        [family_name] => Strehle
        [locale] => de
    )
    

    The solution originated from this thread: https://groups.google.com/forum/#!msg/google-api-php-client/o1BRsQ9NvUQ/xa532MxegFIJ