2015-03-24 169 views
1

我使用TwitterOAuth库构建了一个Twitter应用程序,用于用户身份验证。Twitter OAuth无法检索访问令牌

我能够将用户重定向到Twitter进行身份验证,并接收oauth令牌,oauth secret和oauth验证程序,但是我无法在获取访问令牌的情况下完成身份验证的最后一步。 我开发本地主机上,我已经建立回调路径与

http://127.0.0.1:80/TwitterApp/update.php

我的应用程序读取和写入权限。

这里是我的代码:

的index.php

<?php 
    session_start(); 
    include "twitteroauth/autoload.php"; 
    include "oauthConsts.php"; 

    use Abraham\TwitterOAuth\TwitterOAuth; 

    // request authentication tokens 
    $oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); 
    $request_token = $oauth->getRequestToken(
        'http://127.0.0.1/TwitterApp/update.php'); 

    $_SESSION['oauth_token'] = $request_token['oauth_token']; 
    $_SESSION['oauth_secret'] = $request_token['oauth_token_secret']; 

    if($oauth->getLastHttpCode()==200){ 
     // Let's generate the URL and redirect 
     $url = $oauth->getAuthorizeURL($request_token['oauth_token']); 
     header('Location: '. $url); 
    } else { 
     echo "something went wrong"; 
    } 

?> 

update.php

<?php 
     session_start(); 
     include "twitteroauth/autoload.php"; 
     include "oauthConsts.php"; 

     use Abraham\TwitterOAuth\TwitterOAuth; 

     if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) 
      && !empty($_SESSION['oauth_secret'])) { 
      $oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, 
         $_SESSION['oauth_token'], $_SESSION['oauth_secret']); 
      $access_token = $oauth->oauth("oauth/access_token", 
          array("oauth_verifier" => $_GET['oauth_verifier'])); 

      $_SESSION['access_token'] = $access_token; 

     } 
     else { 
      header('Location: index.php'); 
     } 
    ?> 

在执行时,$中的access_token成为update.php

'{“error”:“无效/过期 令牌”,“请求”:“/ oauth/access_token”}'与HTTP响应状态 401而不是返回认证值。

回答

0

事实证明我的问题是由会话和回调url造成的。

我是通过本地主机/路径访问索引页/到/文件,但Twitter被重定向到127.0.0.1/path/to/file用户认证后,意味着存储在本地主机会话数据127.0.0.1无法访问。

使用127.0.0.1而不是localhost访问索引页解决了这个问题。

相关问题