How can I verify a Google authentication API access token?

前端 未结 10 498
长发绾君心
长发绾君心 2020-11-30 17:19

How can I verify a Google authentication access token?

I need to somehow query Google and ask: Is [given access token] valid for the [exampl

10条回答
  •  粉色の甜心
    2020-11-30 18:05

    Here's an example using Guzzle:

    /**
     * @param string $accessToken JSON-encoded access token as returned by \Google_Client->getAccessToken() or raw access token
     * @return array|false False if token is invalid or array in the form
     * 
     * array (
     *   'issued_to' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
     *   'audience' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
     *   'scope' => 'https://www.googleapis.com/auth/calendar',
     *   'expires_in' => 3350,
     *   'access_type' => 'offline',
     * )
     */
    public static function tokenInfo($accessToken) {
        if(!strlen($accessToken)) {
            return false;
        }
    
        if($accessToken[0] === '{') {
            $accessToken = json_decode($accessToken)->access_token;
        }
    
        $guzzle = new \GuzzleHttp\Client();
    
        try {
            $resp = $guzzle->get('https://www.googleapis.com/oauth2/v1/tokeninfo', [
                'query' => ['access_token' => $accessToken],
            ]);
        } catch(ClientException $ex) {
            return false;
        }
    
        return $resp->json();
    }
    

提交回复
热议问题