简体   繁体   中英

Unable to decode credential from JWT

I am trying to implement the new "Sign in with Google" button as described in https://developers.google.com/identity/gsi/web/guides/display-button .

Everything is fine, and I am able to get a response from the button with "credential" and "g_csrf_token" elements, which I can send to my server. However, using the Google API Client to decode the credential doesn't work. I'm trying to follow the instructions .

Here's my code:

    $id_token = filter_input(INPUT_POST, 'credential');
    $csrfToken = filter_input(INPUT_POST, 'g_csrf_token'); //??? Do we need this?
    
    $client = new Google_Client(['client_id' => $clientid]);
    $client->addScope("email"); // Recommended in another StackOverflow answer but makes no difference
    try {
        $payload = $client->verifyIdToken($id_token);
    } catch(Exception $ex) {
        $errorMessage = "Error in verifyIdToken():" . $ex->getMessage();
        // ...do stuff with the error message
    }
    // ...do stuff with the returned payload

The result is the error message id_token must be passed in or set as part of setAccessToken .

I've updated my Google API Client to v2.11.

I assume that I've missed a step somewhere - can someone help?

Have found a solution, by trial and error! Turns out that $id_token needs to be passed to the client twice, once in setAccessToken() and then again in verifyIdToken() . Omitting setAccessToken fails (like the error message says), but if you pass it in setAccessToken but NOT in verifyIdToken , that doesn't work either.

$id_token = filter_input(INPUT_POST, 'credential');
$client = new Google_Client(['client_id' => $clientid]);
try {
    $client->setAccessToken($id_token);
    $payload = $client->verifyIdToken($id_token);
} catch(Exception $ex) {
    $errorMessage = "Error in verifyIdToken():" . $ex->getMessage();
    // ...do stuff with the error message
}
// ...do stuff with the returned payload

It would nice, if you're at Google and picking this up, if you updated the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM