【问题标题】:WCF REST for Twitter Authorization用于 Twitter 授权的 WCF REST
【发布时间】:2011-11-02 23:35:30
【问题描述】:

我正在研究 WCF REST API 集成,这也是我第一次使用 Twitter API。我在控制台应用程序中编码这些行。请从这里Twitter Doc

找到帮助文档
HttpClient http = new HttpClient("http://twitter.com/statuses/");
http.TransportSettings.Credentials = new NetworkCredential(username, password);
HttpResponseMessage resp = null;
System.Net.ServicePointManager.Expect100Continue = false;

Console.WriteLine("\nPlease enter a command: ");
string command = Console.ReadLine();

while (!command.Equals("q"))
{
    try
    {
        switch (command)
        {
            case "ls public":
                GetStatuses(http, "public_timeline.xml");
                break;
            case "ls friends":
                GetStatuses(http, "friends_timeline.xml");
                break;
            case "ls":
                GetStatuses(http, "user_timeline.xml");
                break;

        }
    }
    catch (Exception ex)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(ex.Message);
        Console.ForegroundColor = ConsoleColor.Yellow;
    }

    Console.WriteLine("\nPlease enter a command: ");
    Console.ReadLine();
}

这是其他代码,

static void GetStatuses(HttpClient http, string uri)
        {
            HttpResponseMessage resp= http.Get(uri);
            resp.EnsureStatusIsSuccessful();
            DisplayTwitterStatuses(resp.Content.ReadAsXElement());
        }

        static void DisplayTwitterStatuses(XElement root)
        {
            var statuses = root.Descendants("status");
            foreach (XElement status in statuses)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write(status.Element("user").Element("screen_name").Value);
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write(" {0} ",status.Element("id").Value);
                Console.ForegroundColor = ConsoleColor.White;
                string text = status.Element("text").Value;
                if (text.Length > 50)
                    text = text.Remove(50) + "....";

                Console.WriteLine(text);
                Console.ForegroundColor = ConsoleColor.Yellow;

            }

        }

如果我选择“ls public”,它会显示公共 xml 数据,但如果我选择“ls friends”或“ls”,即使我的凭据有效,它也会引发授权错误。

Unauthorized (401) is not one of the following: OK (200), Created (201), Accepted (202), NonAuthoritativeInformation (203), NoContent (204), ResetContent (205), PartialContent (206)

请帮我找出解决办法!

【问题讨论】:

  • 您找到解决方案了吗?我也有这个特定的问题。我认为我们需要根据 Oauth 身份验证过程将 access_key 传递给 trow 标头
  • 感谢 silagy,但我仍然面临这个问题。

标签: c# wcf api twitter wcf-rest


【解决方案1】:

为了从 Twitter 或其他提供商 (google..) 获取信息,您需要提供基于 Oauth 1.0 or 2.0 的安全授权

见推特Authentication documentation

为方便起见,您可以协助Matlus basic library See code project on google

他们提供了很好的例子。我已经使用它并且成功了。

基本上你需要处理这些步骤

  1. 在 twitter 中注册您的应用程序并获取客户密钥和客户密钥
  2. 请参阅 twitter 中的授权文档 - link - 请参阅 OAuth 简介部分
  3. 请求请求令牌
  4. 用户授权请求
  5. 请求访问令牌

我使用这个库的代码示例

protected void Page_Load(object sender, EventArgs e)
{
    realm = Request.Url.Scheme + "://" + Request.Url.DnsSafeHost + Request.ApplicationPath;

    if (!IsPostBack)
    {
        if (Request.QueryString["oauth_token"] ==null)
        {
            MakeRequestForToken();
        }
        else
        {
            HandleAuthorizeTokenResponse();
        }
    }



}

private void MakeRequestForToken()
{
    string consumerKey = null;
    string consumerSecret = null;
    string requestTokenEndpoint = null;
    string requestTokenCallback = null;
    string authorizeTokenUrl = null;

    consumerKey = "my customer key";
    consumerSecret = "my customer secret key";

    //Twitter
    requestTokenEndpoint = "https://api.twitter.com/oauth/request_token";

    requestTokenCallback = GetRouteableUrlFromRelativeUrl("oAuthGoolgecsSharp/GoogleOauthTry.aspx");


    //Twitter
    authorizeTokenUrl = "https://api.twitter.com/oauth/authorize";


    if (String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret))
        throw new ArgumentException("Please set up your consumer key and consumer secret for the selected provider", "consumerKey or consumerSecret");

    // Step 1: Make the call to request a token
    var oAuthConsumer = new OAuthConsumer();
    var requestToken = oAuthConsumer.GetOAuthRequestToken(requestTokenEndpoint, realm, consumerKey, consumerSecret, requestTokenCallback);
    PersistRequestToken(requestToken);

    // Step 2: Make a the call to authorize the request token
    Response.Redirect(authorizeTokenUrl + "?oauth_token=" + requestToken.Token);
}

 /// <summary>
/// Step 3: Exchange the Request Token for an Access Token
/// </summary>
private void HandleAuthorizeTokenResponse()
 {
     string consumerKey = null;
     string consumerSecret = null;
     string accessTokenEndpoint = null;
     string token = null;
     string verifier = null;

     provider = "Google";

     token = Request.QueryString["oauth_token"];
     verifier = Request.QueryString["oauth_verifier"];
    //Google
     //accessTokenEndpoint = "https://www.google.com/accounts/OAuthGetAccessToken";

    //Twitter
     accessTokenEndpoint = "https://api.twitter.com/oauth/access_token";

     if (String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret))
         throw new ArgumentException("Please set up your consumer key and consumer secret for the selected provider", "consumerKey or consumerSecret");

     // Exchange the Request Token for an Access Token
     var oAuthConsumer = new OAuthConsumer();
     var accessToken = oAuthConsumer.GetOAuthAccessToken(accessTokenEndpoint, realm, consumerKey, consumerSecret, token, verifier, GetRequesttoken().TokenSecret);
    this.SaveAccessTokken(accessToken);
     Response.Redirect("~/TaksList.aspx");
 }

RequestToken GetRequesttoken()
{
    var requestToken = (RequestToken)Session["RequestToken"];
    Session.Remove("RequestToken");
    return requestToken;
}

void PersistRequestToken(RequestToken requestToken)
{
    Session["RequestToken"] = requestToken;
}

string GetRouteableUrlFromRelativeUrl(string relativeUrl)
{
    var url = HttpContext.Current.Request.Url;
    return url.Scheme + "://" + url.Authority + VirtualPathUtility.ToAbsolute("/" + relativeUrl);
}

private void SaveAccessTokken(AccessToken tokken)
{
    Session.Add("AccessTokken",tokken);
}
  1. 发出网络请求 - 例如http://api.twitter.com/1/statuses/home_timeline.json
  2. 使用 OauthBase.cs 生成签名
  3. 使用 OAuthUtils.cs 和方法调用 GetUserInfoAuthorizationHeader 生成授权标头
  4. 将授权放在请求头中
  5. 发送请求并获取数据

查看我的代码示例 私有AccessToken _accessToken = null;

protected void Page_Load(object sender, EventArgs e)
{
    _accessToken = (AccessToken)Session["AccessTokken"];
    string _customerkey = "my customer key";
    string _customerSecret = "my customer secret key";


    string nostring = "";
    string nnString = "";
    OAuthBase oauth = new OAuthBase();

    //Twitter
    Uri t = new Uri("http://api.twitter.com/1/statuses/home_timeline.xml");
    string u = oauth.GenerateSignature(t, _customerkey, _customerSecret, _accessToken.Token,
                                       _accessToken.TokenSecret, "GET", oauth.GenerateTimeStamp(),
                                       oauth.GenerateNonce(), out nostring, out nnString);

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(nostring);
    request.Method = "GET";


    string realm = Request.Url.Scheme + "://" + Request.Url.DnsSafeHost + Request.ApplicationPath;

    OAuthUtils util = new OAuthUtils();
    AuthorizeHeader h = util.GetUserInfoAuthorizationHeader(t.ToString(), realm, _customerkey, _customerSecret,
                                               _accessToken.Token, _accessToken.TokenSecret,
                                               SignatureMethod.HMACSHA1, "GET");

    request.Headers.Add("Authorization",h.ToString());
    Response.Write(request.Headers["Authorization"].ToString() + "<br />");

    try
    {
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string responseString = reader.ReadToEnd();
        reader.Close();
        Response.Write(responseString);
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
        //throw;
    }





}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-28
    • 2010-09-28
    • 2016-12-10
    • 2014-07-19
    • 2013-07-19
    • 2015-09-16
    • 2014-03-08
    • 1970-01-01
    相关资源
    最近更新 更多