Search code examples
c#twitteroauthtwitter-oauth

Twitter API returning 215 Bad Authentication Data when calling account/verify_credentials.json


I am writing an API which needs to verify the OAuth token and token secrets which are created by the Twitter SDK on mobile devices.

To do this I am attempting to call account/verify_credentials.json of the Twitter API. I have jumped through all the OAuth signature generation hoops yet on every request I get the same response:

{
  "errors": [{
    "code": 215,
    "message": "Bad Authentication data."
  }] 
}

I am at a loss to explain why this is occurring since I have followed Twitter's guidelines and also referenced several other questions with similar goals, yet still without luck.

Also, please note that I do not want to use a library for this. All I need to make is this one single request, so an additional library would be needless bloat. Below is my code which is generating the error response:

var httpMethod = HttpMethod.Get;
var uri = new Uri("https://api.twitter.com/1.1/account/verify_credentials.json");

var nonce = Guid.NewGuid().ToString();
var timestamp = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString(CultureInfo.InvariantCulture);

var oauthParameters = new SortedDictionary<string, string>
{
    {"oauth_consumer_key", Settings.OAuth.Twitter.ConsumerKey},
    {"oauth_nonce", nonce},
    {"oauth_signature_method", "HMAC-SHA1"},
    {"oauth_timestamp", timestamp},
    {"oauth_token", accessToken},
    {"oauth_version", "1.0"}
};

var signingParameters = new SortedDictionary<string, string>(oauthParameters);
var parsedQuery = HttpUtility.ParseQueryString(uri.Query);
foreach (var k in parsedQuery.AllKeys)
    signingParameters.Add(k, parsedQuery[k]);

var parameterString = string.Join("&", signingParameters.Keys.Select(k => $"{Uri.EscapeDataString(k)}={Uri.EscapeDataString(signingParameters[k])}"));

var stringToSign = string.Join("&", new[] { httpMethod.Method.ToUpper(), uri.AbsoluteUri, parameterString }.Select(Uri.EscapeDataString));
var signingKey = Settings.OAuth.Twitter.ConsumerSecret + "&" + tokenSecret;
var signature = Convert.ToBase64String(new HMACSHA1(Encoding.ASCII.GetBytes(signingKey)).ComputeHash(Encoding.ASCII.GetBytes(stringToSign)));

oauthParameters.Add("oauth_signature", signature);
var authHeader = string.Join(",", oauthParameters.Keys.Select(k => $"{Uri.EscapeDataString(k)}=\"{Uri.EscapeDataString(oauthParameters[k])}\""));

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", authHeader);
var response = await client.GetAsync(uri);
return await response.Content.ReadAsStringAsync(); // always error 215

Solution

  • I just tried your code verbatim and it worked like a charm.

    Your issue must be your twitter application keys. Try copying them in from apps.twitter.com again. If that still does not work, you may need to recreate your keys.