Google OAuth通过Zend Framework - 检测拒绝访问

时间:2011-07-25 20:09:31

标签: zend-framework oauth

我正在使用Zend Framework使用OAuth连接Google Web服务(即gmail)。以下代码可以正常工作;但它无法检测拒绝访问。例如,当用户点击“拒绝”时,我会收到一条错误,指出“无法从令牌网址检索有效的令牌响应:请求令牌无效”

以下是代码:

    $THREE_LEGGED_CONSUMER_KEY = 'mydomain.com';
    $THREE_LEGGED_SIGNATURE_METHOD = 'HMAC-SHA1';
    $THREE_LEGGED_CONSUMER_SECRET_HMAC = 'mySecret';
    $THREE_LEGGED_SCOPES = array('https://mail.google.com/');

    $options = array(
                    'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
                    'version' => '1.0',
                    'consumerKey' => $THREE_LEGGED_CONSUMER_KEY,
                    'callbackUrl' => 'http://mydomain.com/oauth',
                    'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
                    'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
                    'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
                );

    $options['signatureMethod'] = 'HMAC-SHA1';
    $options['consumerSecret'] = $THREE_LEGGED_CONSUMER_SECRET_HMAC;

    $consumer = new Zend_Oauth_Consumer($options);

    $conf = new Zend_Config_Ini('../application/configs/application.ini', 'production');
    $db = Zend_Db::factory($conf->database);
    $sql = 'SELECT * FROM gmail_oauth WHERE id=123 LIMIT 1';
    $accessToken = $db->fetchRow($sql);

    if ($accessToken['GoogleAccessToken']=='') {
        if (!isset($_SESSION['REQUEST_TOKEN'])) {
            $_SESSION['REQUEST_TOKEN'] = serialize($consumer->getRequestToken(array('scope' => implode(' ', $THREE_LEGGED_SCOPES))));
            $consumer->redirect(array('hd' => 'default'));
        }
        else {
            $accessToken = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));
            $data = array('GoogleAccessToken'=>$accessToken);
            $db->update('gmail_oauth',$data,'id=123');
            unset($_SESSION['REQUEST_TOKEN']);
        }
    }

    $db->closeConnection();
    return;

当用户点击“拒绝”时抛出异常的代码行是

$accessToken = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));

如何检测拒绝访问?

1 个答案:

答案 0 :(得分:0)

再次回答我自己的问题......

请参阅:http://www.phpriot.com/articles/twitter-authentication-zend-oauth/5

引用:

  

接下来,我们使用Zend_Oauth_Consumer类来检索访问令牌。为此,我们使用getAccessToken()方法。如果无法检索到有效的访问令牌,此方法将抛出异常,因此我们将整个块包装在“try catch”中。