R
R
robert_n2016-02-03 18:19:52
PHP
robert_n, 2016-02-03 18:19:52

Token validation with Google APIs Client Library for PHP?

Hello! Please help me solve the problem related to token verification on the server side.
In an Android application, I receive a token:

GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
 if (result.isSuccess()) {
                GoogleSignInAccount acct = result.getSignInAccount();
                String idToken = acct.getIdToken();
                ...
                // TODO(user): Здесь отпралвяю полученный токен на сервер.
            } else {
                // Show signed-out UI.
            }

I check the token on the server:
function getUserFromToken($token) {
    $client = new Google_Client();
    $client->setClientId(CLIENT_ID);
    $client->setClientSecret(CLIENT_SECRET);
    $client->setRedirectUri('');
    $client->setScopes('email');

    $client->setAccessToken($token);

    $ticket = $client->verifyIdToken();
        if ($ticket) {
            $data = $ticket->getAttributes();
            return $data['payload']['sub']; // user ID
        }
         return false
    }

But the error "id_token must be passed in or set as part of setAccessToken" occurs. There is a suspicion that I screwed up with the access_token somewhere. I read the docs and looked at the examples , but I can’t figure out how to do a simple check of the token so that I get information about the user in response.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2016-02-03
@robert_n

Everything is actually very simple. You have an error in the token verification code. Use the following code:

function getUserFromToken($token) {
    $client = new Google_Client();
    $client->setClientId(CLIENT_ID);
    $client->setClientSecret(CLIENT_SECRET);
    $client->setRedirectUri('');
    $client->setScopes('email');

   $user_data = $client->verifyIdToken($access_token);
   // Здесь работаете с json для получения конкретных данных
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question