Help with request_token


#1

Hi,

I’ve noticed a lot of people having problems getting a proper response when sending a request_token response. I’ve read many other threads and have been unable to get my code to work. I get a 401 Unauthorized response back. Here is what I’m working with and I’m hoping someone can pinpoint the problem:

public string ToQueryString(Dictionary<string, string> collection)
{
       return string.Join("&", collection.Select(match => string.Format("{0}={1}", UrlEncode(match.Key), UrlEncode(match.Value))).ToArray());
}

public string ToHeaderString(Dictionary<string, string> collection)
{
       return string.Join(",", collection.Select(match => string.Format("{0}=\"{1}\"", UrlEncode(match.Key), UrlEncode(match.Value))).ToArray());
}

public string GetRequestTokenResponse()
{
      Dictionary<string, string> parameters = new Dictionary<string, string>();
      parameters.Add("oauth_callback", UrlEncode(RedirectUri));
      parameters.Add("oauth_consumer_key", ClientId);
      parameters.Add("oauth_nonce", new Random().Next(123400, int.MaxValue).ToString("X", CultureInfo.InvariantCulture));
      parameters.Add("oauth_signature_method", SIGNATURE_METHOD);
      parameters.Add("oauth_timestamp", Convert.ToInt64((DateTime.UtcNow - UNIX_EPOCH).TotalSeconds, CultureInfo.CurrentCulture).ToString(CultureInfo.CurrentCulture));
      parameters.Add("oauth_version", OAUTH_VERSION);
      parameters.OrderBy(x => x.Key).ToDictionary(v => v.Key, v => v.Value);

      string oauthSignature = string.Format("POST&{0}&{1}", UrlEncode(TOKEN_URL), UrlEncode(ToQueryString(parameters)));
      oauthSignature = Convert.ToBase64String((new HMACSHA1(Encoding.ASCII.GetBytes(ClientSecret + "&"))).ComputeHash(Encoding.ASCII.GetBytes(oauthSignature)));

      string header = string.Format(HEADER_STRING, ToHeaderString(parameters), UrlEncode(oauthSignature));

      HttpWebRequest request = (HttpWebRequest) WebRequest.Create(string.Format("{0}", TOKEN_URL));
      request.Method = "POST";
      request.ContentLength = 0;
      request.ServicePoint.Expect100Continue = false;
      request.Headers.Add("Authorization", header);

      HttpWebResponse s = (HttpWebResponse)request.GetResponse();
      Stream stream = s.GetResponseStream();
      string responseString = new StreamReader(stream).ReadToEnd();
      return responseString;
}

Thanks.