简体   繁体   中英

WCF REST for Twitter Authorization

I am working on WCF REST API integration, and also This is my first time to work with Twitter API. i code these lines in a console application. Please find the help doc from here 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();
}

here is other codes,

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;

            }

        }

If i select "ls public" it display the public xml datam but if i select "ls friends" or "ls" it throw an error of authorization even if my credential is valid.

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

Please help me to find out the solution!

In order to get information from Twitter or other provider (google..) you need to provide a secure Authorization based on Oauth 1.0 or 2.0

See Twitter Authentication documentation

To make thing easy, you can assist the Matlus basic library See code project on google

They provided very good example. I have used it and successes.

Basically you need to flow those staps

  1. Register your application in twitter and get customer key and customer secret key
  2. See Authorization document in twitter - link - see section Introduction to OAuth
  3. Request for Request token
  4. request for User authorization
  5. request for access token

My code example using this library

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. Make a web request - for example http://api.twitter.com/1/statuses/home_timeline.json
  2. generate signature using OauthBase.cs
  3. Generate Authorization header using OAuthUtils.cs with method call GetUserInfoAuthorizationHeader
  4. Put the Authorization in request header
  5. Send request and get data

See my code example 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;
    }





}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM