Introduction
The OAuth protocol enables websites or applications (Consumers) to access Protected Resources from a web service (Service Provider) via an API, without requiring Users to disclose their Service Provider credentials to the Consumers. More generally, OAuth creates a freely-implementable and generic methodology for API authentication.
OAuth aims to unify the experience and implementation of delegated web service authentication into a single, community-driven protocol. OAuth builds on existing protocols and best practices that have been independently implemented by various websites. An open standard, supported by large and small providers alike, promotes a consistent and trusted experience for both application developers and the users of those applications.
Recently twitter announced API v1.1 and also deprecated v1.0 API support.
In v1.1 twitter is very strict in terms of authentication. We need to create an application for accessing the Twitters API.
Application creation
For creating an application we need to login with our twitters credentials on https://dev.twitter.com/.
After successfully logged-in click on "Create a new application" to create an application.
After that fill the below shown form to create an application.
Provide Application name,description,website URL and call-back URL.
Accept the twitter mentioned rule and regulation and click on "Create your Twitter application" to proceed further and we will see the below screen.
Now we have our Consumer Key and Consumer Secret but we don't have any kind of Access Token and Access Token Secret.
So for generating/creating the access token and access token secret click on "Create Access Token" as shown in below image
We will see below screen with the confirmation
Cheers guys we have successfully created an application for Twitter.
Now its time to write some code for accessing Twitter API.
Using the code
Twitter provides many API if we want we can check here.
We will look into code now.
public void Verify_Credentials()
{
string oauthconsumerkey = "your consumerkey";
string oauthconsumersecret = "your consumer secret key";
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthtoken = "your oauth token";
string oauthtokensecret = "your oauth token secret";
string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", "1.0");
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", "HMAC-SHA1");
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_token", oauthtoken);
StringBuilder baseString = new StringBuilder();
baseString.Append("GET" + "&");
baseString.Append(EncodeCharacters(Uri.EscapeDataString("https://api.twitter.com/1.1/account/verify_credentials.json") + "&"));
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
}
string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);
string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));
ServicePointManager.Expect100Continue = false;
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(
@"https://api.twitter.com/1.1/account/verify_credentials.json");
StringBuilder authorizationHeaderParams = new StringBuilder();
authorizationHeaderParams.Append("OAuth ");
authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
if (!string.IsNullOrEmpty(oauthtoken))
authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
hwr.Headers.Add("Authorization", authorizationHeaderParams);
hwr.Method = "GET";
hwr.ContentType = "application/x-www-form-urlencoded";
hwr.Timeout = 3 * 60 * 1000;
try
{
hwr.Proxy = new WebProxy("enter proxy details/address");
HttpWebResponse rsp = hwr.GetResponse() as HttpWebResponse;
Stream dataStream = rsp.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
catch (Exception ex)
{
}
}
We can have a look at the description of this API over here
public void Search()
{
string url = "https://api.twitter.com/1.1/search/tweets.json?q=your search query";
string oauthconsumerkey = "your consumer key";
string oauthtoken = "your oauth token";
string oauthconsumersecret = "your consumer secret";
string oauthtokensecret = "your oauth token secret";
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthnonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("q", "your search query");
basestringParameters.Add("oauth_version", oauthversion);
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_token", oauthtoken);
StringBuilder baseString = new StringBuilder();
baseString.Append("GET" + "&");
baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
}
string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);
string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(
hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);
StringBuilder authorizationHeaderParams = new StringBuilder();
authorizationHeaderParams.Append("OAuth ");
authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
if (!string.IsNullOrEmpty(oauthtoken))
authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
webRequest.Headers.Add("Authorization", authorizationHeaderParams);
webRequest.Method = "GET";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Timeout = 3 * 60 * 1000;
try
{
webRequest.Proxy = new WebProxy("enter proxy details/address");
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
catch (Exception ex)
{
}
}
We can have a look at the description of this API over here.
public void SendReply()
{
string status = "@screenname Good day";
string postBody = "status=" + Uri.EscapeDataString(status);
string oauth_consumer_key = "your consumerkey";
string oauth_consumerSecret = "your consumer secret";
string oauth_signature_method = "HMAC-SHA1";
string oauth_version = "1.0";
string oauth_token = "your aouth token";
string oauth_token_secret = "your oauth token secret";
string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("in_reply_to_status_id",
"status id of the post to which we are going to reply");
basestringParameters.Add("status", Uri.EscapeDataString(status));
basestringParameters.Add("oauth_version", oauth_version);
basestringParameters.Add("oauth_consumer_key", oauth_consumer_key);
basestringParameters.Add("oauth_nonce", oauth_nonce);
basestringParameters.Add("oauth_signature_method", oauth_signature_method);
basestringParameters.Add("oauth_timestamp", oauth_timestamp);
if (!string.IsNullOrEmpty(oauth_token))
basestringParameters.Add("oauth_token", oauth_token);
StringBuilder baseString = new StringBuilder();
baseString.Append("POST" + "&");
baseString.Append(EncodeCharacters(Uri.EscapeDataString("https://api.twitter.com/1.1/statuses/update.json") + "&"));
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
}
string finalBaseString= baseString.ToString().Substring(0, baseString.Length - 3);
string signingKey = EncodeCharacters(Uri.EscapeDataString(oauth_consumerSecret)) + "&" +
EncodeCharacters(Uri.EscapeDataString(oauth_token_secret));
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(
@"https://api.twitter.com/1.1/statuses/update.json?in_reply_to_status_id=status id");
StringBuilder authorizationHeaderParams = new StringBuilder();
authorizationHeaderParams.Append("OAuth ");
authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",";)
authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauth_signature_method) + "\",");
authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\",");
authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",");
if (!string.IsNullOrEmpty(oauth_token))
authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauth_token) + "\",");
authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",");
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauth_version) + "\"");
webRequest.Headers.Add("Authorization", authorizationHeaderParams);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream stream = webRequest.GetRequestStream();
byte[] bodyBytes = new ASCIIEncoding().GetBytes(postBody);
stream.Write(bodyBytes, 0, bodyBytes.Length);
stream.Flush();
stream.Close();
webRequest.Timeout = 3 * 60 * 1000;
try
{
webRequest.Proxy = new WebProxy("enter proxy details/address");
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
catch (Exception ex)
{
}
}
We can have a look at the description of this API over here.
public void RequestToken()
{
string oauthcallback = "your callback URL";
string oauthconsumerkey = "your consumer key";
string oauthconsumersecret = "your consumer secret";
string oauthtokensecret = string.Empty;
string oauthtoken = string.Empty;
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
string url = "https://api.twitter.com/oauth/request_token?oauth_callback=" + oauthcallback;
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", oauthversion);
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_callback", Uri.EscapeDataString(oauthcallback));
StringBuilder baseString = new StringBuilder();
baseString.Append("POST" + "&");
baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
}
string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);
string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(
hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);
StringBuilder authorizationHeaderParams = new StringBuilder();
authorizationHeaderParams.Append("OAuth ");
authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
webRequest.Headers.Add("Authorization", authorizationHeaderParams);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Timeout = 3 * 60 * 1000;
try
{
webRequest.Proxy = new WebProxy("enter proxy details/address");
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
catch (Exception ex)
{
}
}
We can have a look at the description of this API over here.
public void Authorize()
{
string oauthconsumerkey = "your consumer key";
string oauthconsumersecret = "your consumer secret";
string oauthtokensecret =
"Use the oauth_token_secret you receieved as the result of Request_Token API";
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthtoken = "Use the oauth_token you receieved as the result of Request_Token API";
string url = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauthtoken;
string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", oauthversion);
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
StringBuilder baseString = new StringBuilder();
baseString.Append("GET" + "&");
baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
}
string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);
string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature =
Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);
StringBuilder authorizationHeaderParams = new StringBuilder();
authorizationHeaderParams.Append("OAuth ");
authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
if (!string.IsNullOrEmpty(oauthtoken))
authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
webRequest.Headers.Add("Authorization", authorizationHeaderParams);
webRequest.Method = "GET";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Timeout = 3 * 60 * 1000;
try
{
webRequest.Proxy = new WebProxy("enter proxy details/address");
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
catch (Exception ex)
{
}
}
private string EncodeCharacters(string data)
{
if (data.Contains("!"))
data = data.Replace("!", "%21");
if (data.Contains("'"))
data = data.Replace("'", "%27");
if (data.Contains("("))
data = data.Replace("(", "%28");
if (data.Contains(")"))
data = data.Replace(")", "%29");
if (data.Contains("*"))
data = data.Replace("*", "%2A");
if(data.Contains(","))
data = data.Replace(",", "%2C");
return data;
}
- Verify_Credentials API: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/get/account/verify_credentials
- Search API: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/get/search/tweets
- Statuses/Update API: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/post/statuses/update
- Request_Token API: We can have a look at the description of this API over https://dev.twitter.com/oauth/reference/post/oauth/request_token
- Authorize API: We can have a look at the description of this API over https://dev.twitter.com/oauth/reference/get/oauth/authorize
Useful Trick
Check the oauth tool for the basestring.It gives us the option to check whether code generated basestring and tool generated basestring are same or not. If it is same then good to go but if code generated basestring is different from tool's basestring then we need to look at our code to make it equal.
As per OAuth Core 1.0, Characters in the unreserved character set MUST NOT be encoded and rest of the characters must be encoded.
unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
References
I am not smart enough to write this article on my own. So here is the list of references: