Retrieving the twitter identity

By | Apr 14, 2017

In the previous article I showed how to use OAuth to connect to twitter. At this point all the authentication and authorization has been done and we are busy with the last step to retrieve the Identity information from twitter specifically.

Just for reference I am including the image of the components involved with Oauth.

The code below connects to twitter and retrieves the identity information in JSON format.

string oAuthProviderUri = "";
string identityRequestUri = oAuthProviderUri + "/1.1/account/verify_credentials.json";
string authHeader = OAuthMan.GenerateAuthzHeader(identityRequestUri, "GET");

Uri userCredentialUri = new Uri(identityRequestUri);

string userInfo = retrieveUserInformation(userCredentialUri, authHeader);

The following method reads the incoming response and returns a JSON string.

private string retrieveUserInformation(Uri uri, string authHeader)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "x-www-form-urlencoded";

request.Headers["Authorization"] = authHeader;

WebResponse response = null;
Stream receiveStream = null;
StringBuilder responseResult = new StringBuilder();
response = request.GetResponse();
receiveStream = response.GetResponseStream();

Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);
Char[] read = new Char[256];

// Reads 256 characters at a time.
int count = readStream.Read(read, 0, 256);
while (count > 0)
String str = new String(read, 0, count);
count = readStream.Read(read, 0, 256);

return responseResult.ToString();

Next I decode the JSON and read it into a a more usable format.

dynamic jsonTwitterIdentity = Json.Decode(userInfo);

TwitterIdentity twitterIdentity = new TwitterIdentity();
twitterIdentity.Id =;
twitterIdentity.Name =;
twitterIdentity.Description = jsonTwitterIdentity.description;
twitterIdentity.ScreenName = jsonTwitterIdentity.screen_name;
twitterIdentity.Location = jsonTwitterIdentity.location;
twitterIdentity.Language = jsonTwitterIdentity.lang;
0 0 vote
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments