【问题标题】:How to post Twitter message to authenticated user's timeline via OAuth如何通过 OAuth 将 Twitter 消息发布到经过身份验证的用户的时间线
【发布时间】:2012-11-20 22:51:30
【问题描述】:

我已经与 Twitter API 搏斗了几天,但我无法将消息发布到经过身份验证的用户的时间线。我有一个 ASP.NET MVC 4 应用程序,它通过 Twitter 登录用户并保存从登录过程返回的访问令牌。那部分工作正常。我可以在经过身份验证的用户的 Twitter 帐户中看到我的应用程序具有读写权限。

然后,我将使用该访问令牌以及与我的 Twitter 应用程序关联的消费者密钥、消费者密钥和 oauth 令牌密钥发布到用户的时间线。我每次都会收到 401 未经授权的错误。我尝试使用 1.1 API 和 1 API 得到相同的结果。

大部分代码来自 Gary Short 的文章:http://garyshortblog.wordpress.com/2011/02/11/a-twitter-oauth-example-in-c/

这是我到目前为止所得到的。如果有人能发现任何关于我缺少什么的线索,我将不胜感激。

    public async Task<bool> Push(TwitterMessage twitterMessage)
    {
        const string updateApi = "http://api.twitter.com/1/statuses/update.json";
        const string oauthConsumerKey = "<consumerKey>";
        const string consumerSecret = "<consumerSecret>";
        const string oauthSignatureMethod = "HMAC-SHA1";
        const string oauthTokenSecret = "<tokenSecret>";
        var signingKey = string.Format("{0}&{1}", consumerSecret.Escaped(), oauthTokenSecret.Escaped());

        var postBody = "status=" + Uri.EscapeDataString(twitterMessage.MessageContent);
        var oauthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        var oauthToken = "<authenticatedUserToken>";
        var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        var oauthTimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

        var message = string.Format("POST {0}?{1} HTTP/1.1", updateApi, postBody.Escaped());
        var hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
        var signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(message)));

        ServicePointManager.Expect100Continue = false;

        var request = (HttpWebRequest)WebRequest.Create(updateApi);
        request.KeepAlive = false;

        var authorisationBuilder = new StringBuilder();
        authorisationBuilder.Append("OAuth ");
        authorisationBuilder.AppendFormat("oauth_consumer_key=\"{0}\",", oauthConsumerKey.Escaped());
        authorisationBuilder.AppendFormat("oauth_signature_method=\"{0}\",", oauthSignatureMethod.Escaped());
        authorisationBuilder.AppendFormat("oauth_timestamp=\"{0}\",", oauthTimestamp.Escaped());
        authorisationBuilder.AppendFormat("oauth_nonce=\"{0}\",", oauthNonce.Escaped());
        authorisationBuilder.AppendFormat("oauth_token=\"{0}\",", oauthToken.Escaped());
        authorisationBuilder.AppendFormat("oauth_signature=\"{0}\"", signatureString.Escaped());
        var authorisation = authorisationBuilder.ToString();
        request.Headers.Add("Authorization", authorisation);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        using (var stream = await request.GetRequestStreamAsync())
        {
            var bodyBytes = new ASCIIEncoding().GetBytes(postBody);
            stream.Write(bodyBytes, 0, bodyBytes.Length);
        }

        //Allow us a reasonable timeout in case Twitter's busy
        request.Timeout = 3 * 60 * 1000;

        try
        {
            var response = await request.GetResponseAsync() as HttpWebResponse;
            return true;
        }
        catch (WebException)
        {
            return false;
        } 
    }

    public static string Escaped(this string input)
    {
        return Uri.EscapeDataString(input);
    }

更新 看看这个SO post,我似乎无法使用我一直在做的 DotNetOpenAuth twitter 客户端进行授权。那里的建议是扩展 twitter 消费者类而不是执行授权,这将允许我检索用户的令牌秘密(我认为我的难题中缺少的部分)。当我得到这个工作时会发布另一个更新。

【问题讨论】:

  • 您是否逐行确认发送到服务器的内容是您应该发送的内容?
  • 我使用 Twitter API 控制台发出了一些请求,并验证了我发送的数据与那些完全相同。可能是我需要在发布请求中添加更多信息然后我发送但我不确定
  • 您如何验证您发送的数据完全相同?您是否在发送数据之前验证过,待处理的数据是否完全相同?如果您收到授权错误,您必须做一些不同的事情。
  • 我在var response = await request.GetResponseAsync() as HttpWebResponse; 行设置了一个断点,并查看了授权和帖子正文值。一切似乎都井井有条,但我可能没有发布正确的数据。我已经看到对其他 SO 帖子的回复,指出服务器时间未与 Twitter 同步导致问题,但我在本地运行,而且我的服务器时钟是准确的。
  • 看看这个SO post,它可能与编码有关 - 我今晚回到项目时会检查一下。

标签: c# oauth asp.net-mvc-4 twitter-oauth


【解决方案1】:

所以问题是 DotNetOpenAuth 目前存在的问题。对于 Twitter 身份验证,DotNetOpenAuth 客户端不允许完整的授权流程(需要发布到用户的时间线)。仅从初始握手中检索访问令牌,而不是访问令牌秘密。我使用的是与我的 Twitter 应用程序关联的访问令牌密码,而不是登录的 Twitter 用户,因此每次授权都失败。

更新:我终于开始使用 Daniel Crenna's Tweetsharp 库,这使得代码比编写自己的 API 包装器要简单一些:

public async Task<bool> Push(TwitterAccount account)
{
    var twitterService = new TwitterService(consumerKey, consumerSecret);
    twitterService.AuthenticateWith(account.AccessToken, account.AccessTokenSecret);
    var options = new SendTweetOptions {Status = string.Format("{0} {1}", account.Message.MessageContent, account.Message.ShortLink)};
    var status = twitterService.SendTweet(options);
    return status != null;
}

【讨论】:

    【解决方案2】:

    检查此代码和链接/文章简单易行:

    protected void btnTweet_Click(object sender, EventArgs e)
    {
     string oauthAccessToken = Session["twtoken"].ToString();
     string oauthAccessTokenSecret = Session["twsecret"].ToString();
    
     OAuthHelper oauthhelper = new OAuthHelper();
     oauthhelper.TweetOnBehalfOf(oauthAccessToken, oauthAccessTokenSecret, txtTweet.Text);
    
     if (string.IsNullOrEmpty(oauthhelper.oauth_error))
          Response.Write("Twit Posted Successfully");
     else
          Response.Write(oauthhelper.oauth_error);
    }
    

    阅读更多如何获取访问令牌和密钥以及下载 OAuthHelper 和 OAuthUtility 类的链接如下 -

    How to post tweet on behalf of an user from asp.net using oauth authentication

    Login with twitter using oauth authentication in asp.net and get access token, screen name and userid

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 2019-11-10
      • 2013-06-08
      • 2018-12-16
      • 2017-11-11
      • 2016-01-17
      • 1970-01-01
      相关资源
      最近更新 更多