用于Twitter授权的WCF REST

本文关键字:WCF REST 授权 Twitter 用于 | 更新日期: 2023-09-27 18:06:45

我正在做WCF REST API集成,这也是我第一次使用Twitter API。我在控制台应用程序中编写了这些行代码。请从这里找到帮助文档Twitter文档

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)

请帮我找出解决办法!

用于Twitter授权的WCF REST

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

参见Twitter Authentication文档

为了使事情变得简单,您可以帮助matlab基本库查看google上的代码项目

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

基本上你需要流动这些小针

  1. 在twitter上注册您的应用程序并获得客户密钥和客户密钥
  2. 见twitter中的授权文件-链接-见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. 发出web请求-例如http://api.twitter.com/1/statuses/home_timeline.json
  2. 使用OauthBase.cs生成签名
  3. 使用OAuthUtils.cs与GetUserInfoAuthorizationHeader方法调用生成授权头
  4. 将授权写入请求头
  5. 发送请求和获取数据

参见我的代码示例private 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;
    }


}