401 authorization


#1

I’m trying to complete the first step of signing in with twitter by posting to https://api.twitter.com/1.1/oauth/request_token. I’ve tested my signature string using an expression tester at http://quonos.nl/oauthTester/ and used their dummy data to test my code, both of which worked. I believe may be using HttpWebCLient incorrectly or a problem with oauth_callback string I’m currently using. I’ve included a all of my code (old keys) and relevant libraries used. Can you tell me what’s wrong?

signature key =qbnhoaMIcJmXKx9O65vc13ABkzs=

Authorization: Oauth oauth_consumer_key=“fbpvyf2acxvtc8axbsbgGssDK”, oauth_nonce=“NjM1MzkzMTQ5MDExODQyMTE0”, oauth_signature=“qbnhoaMIcJmXKx9O65vc13ABkzs%3D”, oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1403736101”, oauth_version=“1.0”

signature_string=POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_consumer_key%3Dfbpvyf2acxvtc8axbsbgGssDK%26oauth_nonce%3DNjM1MzkzMTQ5MDExODQyMTE0%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1403736101%26oauth_version%3D1.0

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Security.Cryptography; using System.IO; using System.Globalization;

namespace ConsoleApplication1
{
class TwitterApp
{

    private static string CONSUMER_KEY = "fbpvyf2acxvtc8axbsbgGssDK";
    private static string CONSUMER_SECRET = "2dSgDnGq1xn7fOSTo7gd9H6BzdqyymThkVM4VDFLTLPjAJueer";
    private static string STR_URL ="https://api.twitter.com/oauth/request_token";
    private static string OAUTH_SIGNATURE_METHOD = "HMAC-SHA1";
    private static string OAUTH_VERSION = "1.0";
    private static string OAUTH_TOKEN = "201555372-tJ7vR33pFeQTFPVNLYbKnYfOdngILaeEhmnXH3dK";
    private static string OAUTH_TOKEN_SECRET ="KHgKOie82SdK8w4Hmu6tcprTFrFggTYpfm68sAxZlOzY9";
    private static int TIME_STAMP=0;

    private static int request_count = 0;
    private static byte[] nonce_bytes = new byte[31];
    private static string unique_nonce_string = null;

    public string gCONSUMER_KEY { get { return CONSUMER_KEY; } }
    public string gCONSUMER_SECRET { get { return CONSUMER_SECRET; } }
    public string gOAUTH_SIGNATURE_METHOD { get { return OAUTH_SIGNATURE_METHOD; } }
    public string gOAUTH_VERSION { get { return OAUTH_VERSION; } }
    public string gOAUTH_TOKEN { get { return OAUTH_TOKEN; } }
    public string gOAUTH_TOKEN_SECRET { get { return OAUTH_TOKEN; } }
    public string gTIME_STAMP { get { return TIME_STAMP.ToString(); } }
    public string g_unique_nonce_string { get { return unique_nonce_string; } }  


    private static Random rand=new Random();


  public TwitterApp()
    {

    }

  public static void CreateNonce()
    {
        // create a new nonce key if null
        if (nonce_bytes == null)
        {
            rand.NextBytes(nonce_bytes);
            request_count = 0;
        }

    }

  public static string GetOauthSignature()
  {



      var parameter_string = Uri.EscapeDataString("oauth_consumer_key") + "=" + Uri.EscapeDataString(TwitterApp.CONSUMER_KEY) + "&" +
                             Uri.EscapeDataString("oauth_nonce")+ "=" + Uri.EscapeDataString(TwitterApp.unique_nonce_string) + "&" +
                             Uri.EscapeDataString("oauth_signature_method")+"=" + Uri.EscapeDataString(TwitterApp.OAUTH_SIGNATURE_METHOD )+ "&"+
                             Uri.EscapeDataString("oauth_timestamp")+ "=" + Uri.EscapeDataString(TwitterApp.TIME_STAMP.ToString()) + "&"+
                                                        Uri.EscapeDataString("oauth_version") + "=" + Uri.EscapeDataString(TwitterApp.OAUTH_VERSION);

      var signature_base_string = "POST" + '&' + Uri.EscapeDataString(STR_URL) + '&' + Uri.EscapeDataString(parameter_string);
      var signing_key = Uri.EscapeDataString(TwitterApp.CONSUMER_SECRET) + "&";

      var hmac = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(signing_key));
      byte[] result = hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(signature_base_string));

      return Convert.ToBase64String(result);


  }
  public static void DateTimeToUnixTimestamp()
  {
      TIME_STAMP= (int)(DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
  }

  public static void GenerateUniqueNonce()
  {


      TwitterApp.unique_nonce_string = Convert.ToBase64String(new ASCIIEncoding().GetBytes( DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)));

  }


}

class Authorize : TwitterApp
{
   public Authorize() { }

    public string GetAuthorizationHeader(TwitterApp AuthorizeApp)
   {
       TwitterApp.CreateNonce();
        TwitterApp.GenerateUniqueNonce();
        TwitterApp.DateTimeToUnixTimestamp();

        string signature_string = TwitterApp.GetOauthSignature();

        var QUOTE = "\"";
        var QUOTE_COMMA = "\","+" ";
        string Authorization = Uri.EscapeDataString("oauth_consumer_key") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.gCONSUMER_KEY) + QUOTE_COMMA +
                Uri.EscapeDataString("oauth_nonce") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.g_unique_nonce_string) + QUOTE_COMMA +
               // Uri.EscapeDataString("oauth_callback") + "=" + QUOTE + Uri.EscapeDataString("oob") + QUOTE_COMMA +
                Uri.EscapeDataString("oauth_signature") + "=" + QUOTE + Uri.EscapeDataString(signature_string) + QUOTE_COMMA +
                Uri.EscapeDataString("oauth_signature_method") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.gOAUTH_SIGNATURE_METHOD) + QUOTE_COMMA +
                Uri.EscapeDataString("oauth_timestamp") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.gTIME_STAMP) + QUOTE_COMMA +

                Uri.EscapeDataString("oauth_version") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.gOAUTH_VERSION) + QUOTE;

        return Authorization;
    }
}


class Program
{
    static void Main(string[] args)
    {
        Uri test = new Uri("https://api.twitter.com/1.1/oauth/request_token");

        HttpWebRequest TwRequest = (HttpWebRequest)WebRequest.Create(test);
        HttpWebResponse TwResponse;

        TwRequest.Method = "POST";
        TwRequest.ContentType = "application/x-www-form-urlencoded";

        TwitterApp MyApp = new TwitterApp();
        Authorize RestAuthorize = new Authorize();

        string auth_header = RestAuthorize.GetAuthorizationHeader(MyApp);
        auth_header = "Oauth "+ auth_header;

        TwRequest.Headers.Add("Authorization", auth_header);
        byte[] post_data = System.Text.Encoding.ASCII.GetBytes(auth_header);



        StreamWriter writer = new StreamWriter(TwRequest.GetRequestStream());


        Console.WriteLine(TwRequest.Headers.ToString());

        Stream newStream = TwRequest.GetRequestStream();
        var transmit =System.Text.Encoding.ASCII.GetBytes("oauth_callback" +"="+ "\""+ "oob"+ "\"");
        newStream.Write(transmit, 0, transmit.Length);
        newStream.Close();

        try
        {
            TwResponse = (HttpWebResponse)TwRequest.GetResponse();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.ReadLine();
        }





    }
}

}