php 为什么我的 twitter oauth 访问令牌无效/过期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14502411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is my twitter oauth access token invalid / expired
提问by Finglish
I am using Twitter to log users into to a website, which seems to be working up until I attempt to obtain a valid Access Token.
我正在使用 Twitter 将用户登录到一个网站,在我尝试获取有效的访问令牌之前,该网站似乎一直在工作。
require("twitteroauth.php");
require 'twconfig.php';
session_start();
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET);
$request_token = $twitteroauth->getRequestToken('http://****/tw_response.php');
$oauth_token = $request_token['oauth_token'];
$_SESSION['oauth_token'] = $oauth_token;
$oauth_token_secret = $request_token['oauth_token_secret'];
$_SESSION['oauth_token_secret'] = $oauth_token_secret;
if ($twitteroauth->http_code == 200) {
url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '.$url);
} else {
die('Something wrong happened.');
}
This seems to be working correctly, redirecting me to twitter to sign in and confirm access, after which it returns me to tw_response.php (my Callback url), with the following variables in the url:
这似乎工作正常,将我重定向到 twitter 以登录并确认访问,之后它将我返回到 tw_response.php(我的回调 url),url 中包含以下变量:
http://example.com/login.php?oauth_token=sO3X...yj0k&oauth_verifier=Ip6T...gALQ
In tw_response.php I then try to get the Access Token, but it reports as invalid. I tried using var_dumpto view the content of the access token as follows:
在 tw_response.php 中,我尝试获取访问令牌,但它报告为无效。我尝试使用var_dump查看访问令牌的内容如下:
require("twitteroauth.php");
require 'twconfig.php';
session_start();
$oauth_verifier = $_REQUEST['oauth_verifier'];
$oauth_token = $_SESSION['oauth_token'];
$oauth_token_secret = $_SESSION['oauth_token_secret'];
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
$access_token = $twitteroauth->getAccessToken($data['oauth_verifier']);
var_dump($access_token);
The result of the var_dumpends in "invalid / expired Token":
var_dump以“无效/过期令牌”结尾的结果:
array(8) {
["oauth_url"] => string(104) ""1.0" encoding="UTF-8"?>/oauth/access_token?oauth_consumer_key=ceE...9Dg"
["oauth_nonce"]=> string(32) "c52...d07"
["oauth_signature"]=> string(28) "ry7...Fcc="
["oauth_signature_method"]=> string(9) "HMAC-SHA1"
["oauth_timestamp"]=> string(10) "1359031586"
["oauth_token"]=> string(40) "sO3...j0k"
["oauth_verifier"]=> string(43) "Ip6...ALQ"
["oauth_version"]=> string(63) "1.0 Invalid / expired Token "
}
回答by Amelia
$access_token = $twitteroauth->getAccessToken($data['oauth_verifier']);
var_dump($access_token);
Where did $datamagically come from? You have the variable $oauth_verifier, but keep in mind you don't need this if this is your registered callback URL.
哪里$data奇迹般地从何而来?您有变量$oauth_verifier,但请记住,如果这是您注册的回调 URL,则您不需要它。
Since you used an invalid variable inside getAccessToken, it will return an invalid value back.
由于您在 内部使用了无效变量getAccessToken,因此它将返回无效值。
The correct way to use TwitterOAuth:
使用 TwitterOAuth 的正确方法:
if (!isset($_GET["oauth_token"])) {
// set these values in a config file somewhere.
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
// append a ?. This is your callback URL if you specify something.
$credentials = $twitter->getRequestToken("http://example.com/test.php?");
// try and be a bit more elegant with the URL... This is a minimal example
$url = $twitter->getAuthorizeUrl($credentials);
echo $url;
// these are temporary tokens that must be used to fetch the new,
// permanent access tokens. store these in some way,
// session is a decent choice.
$_SESSION["token"] = $credentials["oauth_token"];
$_SESSION["secret"] = $credentials["oauth_token_secret"];
} else {
// use the user's previously stored temporary credentials here
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$_SESSION["token"], $_SESSION["secret"]);
// uses the oauth_token (from the request) already.
// you store these credentials in your database (see below).
$credentials = $twitter->getAccessToken($_GET["oauth_verifier"]);
// just a printout of credentials. store these, don't display them.
echo "<pre>";
var_dump($credentials);
// valid credentials, provided you give the app access to them.
echo "</pre>";
}
I just use a single script for callbacks for ease of use; you can split the relevant sections into multiple scripts if you like (and you probably should).
为了便于使用,我只使用单个脚本进行回调;如果您愿意(并且您可能应该这样做),您可以将相关部分拆分为多个脚本。
Handily for your database, the credentials include the twitter user's username, too.
Edit: Twitter is now allocating 64bit integers for user IDs. You should store this as a stringto ensure that you don't end up with mangled user IDs and collisions if you can't handle 64bit integers in every part of your application.
对于您的数据库来说,凭证也包括 Twitter 用户的用户名,这很方便。
编辑:Twitter 现在为用户 ID 分配 64 位整数。如果您无法在应用程序的每个部分处理 64 位整数,您应该将其存储为一个字符串,以确保最终不会出现错误的用户 ID 和冲突。
array(4) {
["oauth_token"]=>
string(50) "7041...wYupkS"
["oauth_token_secret"]=>
string(42) "O9ENq...21B2fk"
["user_id"]=> // user ID. always the same, never changes (store this as ID)
string(9) "..."
["screen_name"]=> // username. can change.
string(11) "..."
}
So, if you want to log users in through twitter, without explicitly giving them a login to your site, you could use $_SESSION(I use databases for my logins, which is recommended if you want to save that state)
In the above script you would add this to the end of the elseblock:
因此,如果您想通过 twitter 登录用户,而无需明确让他们登录您的网站,您可以使用$_SESSION(我使用数据库进行登录,如果您想保存该状态,建议您这样做)在上面的脚本中,您将将此添加到else块的末尾:
$_SESSION["token"] = $credentials["oauth_token"];
$_SESSION["secret"] = $credentials["oauth_secret"];
$_SESSION["username"] = $credentials["screen_name"];
You can also get the user's screen name and more from GET account/verify_credentials, if you want to give them a user page (if you use javascript, grab their userid through id_strhere):
GET account/verify_credentials如果你想给他们一个用户页面,你还可以从 获取用户的屏幕名称和更多信息(如果你使用 javascript,通过id_str这里获取他们的用户 ID ):
$user_array = $twitter->get("account/verify_credentials");
回答by Zack Morris
If your OAuth flow was working one day and failing the next, check your computer's clock. I was running a Vagrant box that somehow had its time set to the day before, which caused the Twitter API to return {"code":89,"message":"Invalid or expired token."}. This may also appear as 401 timestamp out of bounds. You can use this command to update your clock in Ubuntu:
如果您的 OAuth 流程在某一天正常运行而在下一天失败,请检查您计算机的时钟。我正在运行一个 Vagrant 盒子,它以某种方式将时间设置为前一天,这导致 Twitter API 返回 {"code":89,"message":"Invalid or expired token."}。这也可能显示为 401 时间戳越界。您可以使用此命令在 Ubuntu 中更新您的时钟:
sudo ntpdate time.nist.gov
Alternative methodif ntpdateisn't available on your system:
如果ntpdate在您的系统上不可用,则替代方法:
sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z"

