Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Add twitter login authentication to website in asp.net

May 7, 2012
Introduction

In this article I will explain how to create app in twitter and implement twitter login authentication for website in asp.net.
Description:
  
In previous post I explained article how to integrate facebook login authentication for website in asp.net. Now I will explain how to allow users to login with twitter accounts in website using asp.net.

Before implement twitter login authentication we need to get consumerKey and consumerSecret key from twitter for that we need to create application in twitter by using this link https://dev.twitter.com/apps/new  once open that will display window like this


Once app page opened enter Application Name, Description, website (Ex: http://aspdotnet-suresh.com) and callback url details and click create new application button and here one more thing we need to remember is twitter won’t support for localhost sites (ex: http://localhost/Default.aspx) because of that we need to give hosted domain site url. 

If you want to test this with your local application no worries check this post how host website in IIS with custom URL .Once our app created in twitter that would be like as shown below image here we can change logo of our application

 
Now create new application using visual studio and write following code aspx page

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1">
<title>Twitter Login Authentication for Website in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ImageButton ID="imgTwitter" runat="server" ImageUrl="~/TwitterSigning.png"
onclick="imgTwitter_Click" />
<table id="tbleTwitInfo" runat="server" border="1" cellpadding="4" cellspacing="0" visible="false">
<tr>
<td colspan="2"><b>Twitter User Profile</b></td>
</tr>
<tr>
<td><b>UserName:</b></td>
<td><%=username%></td>
</tr>
<tr>
<td><b>Full Name:</b></td>
<td><%=name%></td>
</tr>
<tr>
<td><b>Profile Image:</b></td>
<td><img src="<%=profileImage%>" /></td>
</tr>
<tr>
<td><b>Twitter Followers:</b></td>
<td><%=followersCount%></td>
</tr>
<tr>
<td><b>Number Of Tweets:</b></td>
<td><%=noOfTweets%></td>
</tr>
<tr>
<td><b>Recent Tweet:</b></td>
<td><%=recentTweet%></td>
</tr>
</table>
</form>
</body>
</html>
Now in code behind add following namespaces

C# Code


using System;
using System.Web.UI;
using System.Xml;
using oAuthExample;
After completion of adding namespaces write following code in code behind

string url = "";
string xml = "";
public string name = "";
public string username = "";
public string profileImage = "";
public string followersCount = "";
public string noOfTweets = "";
public string recentTweet = "";

protected void Page_Load(object sender, EventArgs e)
{
GetUserDetailsFromTwitter();
}
private void GetUserDetailsFromTwitter()
{
if(Request["oauth_token"]!=null & Request["oauth_verifier"]!=null)
{
imgTwitter.Visible = false;
tbleTwitInfo.Visible = true;
var oAuth = new oAuthTwitter();
//Get the access token and secret.
oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]);
if (oAuth.TokenSecret.Length > 0)
{
//We now have the credentials, so make a call to the Twitter API.
url = "http://twitter.com/account/verify_credentials.xml";
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);
XmlDocument xmldoc=new XmlDocument();
xmldoc.LoadXml(xml);
XmlNodeList xmlList = xmldoc.SelectNodes("/user");
foreach (XmlNode node in xmlList)
{
name = node["name"].InnerText;
username = node["screen_name"].InnerText;
profileImage = node["profile_image_url"].InnerText;
followersCount = node["followers_count"].InnerText;
noOfTweets = node["statuses_count"].InnerText;
recentTweet = node["status"]["text"].InnerText;
}
}
}
}
protected void imgTwitter_Click(object sender, ImageClickEventArgs e)
{
var oAuth = new oAuthTwitter();
if (Request["oauth_token"] == null)
{
//Redirect the user to Twitter for authorization.
//Using oauth_callback for local testing.
oAuth.CallBackUrl = "http://aspdotnet-suresh.com/TwitterAuthentication.aspx";
Response.Redirect(oAuth.AuthorizationLinkGet());
}
else
{
GetUserDetailsFromTwitter();
}
}
If you observe above code I used oAuthTwitter class file you can get this class file from downloadable code. Now get consumerKey and consumerSecret key from twitter and add it in web.config file like this

<appSettings>
<add key="consumerKey" value="Gyew474of7tpEBqnpDw" />
<add key="consumerSecret" value="ytgklq3b8lkxgPShCWeawqzrYpUa1bgsaeGRwW" />
</appSettings>
Demo

 
 Download sample code attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

85 comments :

Anonymous said...

INDEED YOUR THE BEST...

murat said...

Thank you very much,but have can I get the user mail address?

Anonymous said...

hi,

excellent blog .

thanks ,
Ajay

vishal said...

http://api.twitter.com/1/account/verify_credentials.xml. The response contains the user id, screen name etc. but not the email ID.

Is it possible at all to retrieve the email ID of the user?

avinash mane said...

best one yarrr thank u....

♥ ครђ๏кஇ said...

thank u but how to get followers/following users images using asp.net

ravi said...

hello sureshbhai.. I follow your article for login using facebook in website..now i want that get user login data like email ,paassword for storing in our database..and i also want how to get this data at server side means how to get username,password etc on server side to store it on our database

raj said...

Hi...But how to get other details like firstname,lastname,email,city,state etc....

Anonymous said...

32

Anonymous said...

Hi sureshbhai i got this error on return url,
The remote server returned an error: (404) Not Found.

swati awasthi said...

Once i click on Authrize app im getting a window with pin number and it ask me to type it in my website

Anonymous said...

Hey Suresh good example, I did the same thing and am getting a 404 exception. Not sure whats wrong though..

Naisargee Danech said...

Again thanks sir...

Anonymous said...

Yeah ,it doesn't work anymore I guess something changed by twitter.

url = "http://twitter.com/account/verify_credentials.xml";
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);

after this line I get 404 error.

Anonymous said...

Change the foolwing url with
http://api.twitter.com/1/account/verify_credentials.xml

it worked

Vijay kallempudi said...

Really nice article

Anonymous said...

I seriouslу love уour blog.. Very nice сolors &
thеme. Did you develοp thіѕ
amazing site yoursеlf? Рlеase reply
back as I'm looking to create my own personal website and want to learn where you got this from or what the theme is named. Thanks!

Also visit my weblog -
my web page:

Anonymous said...

Pls reflesh the source code links

meera said...

it does.nt work

url = "http://api.twitter.com/1/account/verify_credentials.xml";
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);

after this it gives error

The remote server returned an error: (400) Bad Request.

NileshParmar said...

Hello
Sir,
Really a very nice blog...but i am fresher dev
So i have task to do the twitter integration
I have follow your code but how i get the
<add key="consumerKey"
<add key="consumerSecret"

of the individual user ...
please suggest what i suppose to do ...

NileshParmar said...
This comment has been removed by the author.
meera said...

https://dev.twitter.com/apps/new

you can get <add key="consumerKey"
<add key="consumerSecret"

on this link

Kalai Arasi said...

It does not work for me.
I got the following Error,
-----------------------------------------------
Server Error in '/ThanthiTv' Application.
The remote server returned an error: (404) Not Found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (404) Not Found.

Source Error:


Line 294: finally
Line 295: {
Line 296: webRequest.GetResponse().GetResponseStream().Close();
Line 297: responseReader.Close();
Line 298: responseReader = null;


Source File: c:\kalai\website\Thanthi\App_Code\oAuthTwitter.cs Line: 296


Any Solution ?

Kalai Arasi said...

Following Code will work,XML ends on 2012.Here Use JSON
-----------------------------------------------
if (oAuth.TokenSecret.Length > 0)
{
//We now have the credentials, so make a call to the Twitter API.

url = "https://api.twitter.com/1.1/account/verify_credentials.json";
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);

JObject o = JObject.Parse(xml);
name = Convert.ToString(o["name"]);
username = Convert.ToString(o["screen_name"]);
profileImage = Convert.ToString(o["profile_image_url"]);
followersCount = Convert.ToString(o["followers_count"]);
noOfTweets = Convert.ToString(o["statuses_count"]);
recentTweet = Convert.ToString(o["status"]["text"]);
}

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
R koyee said...

Hello,
It doesn't work it gives error 401 ... Any solutions,Please?
Regards

R koyee said...

I solved the problems :)
after long time trying I figured out those changes:
1- Open oAuthTwitter.cs file.
2- Change the links as follow:

public const string REQUEST_TOKEN = "https://api.twitter.com/oauth/request_token";
public const string AUTHORIZE = "https://api.twitter.com/oauth/authorize";
public const string ACCESS_TOKEN = "https://api.twitter.com/oauth/access_token";
private string _callBackUrl = "http://127.0.0.1:12345/"; // your app link or any other link...

This problem occure because Twitter has changed the links from(http to https )

this works for me .

F Aditya A Wibawa said...

Thanks, with modified code in some user comment in your blog. It works

tejal parikh said...

hey,It gives me error :
The remote server returned an error: (401) Unauthorized.

Vipin said...

Nice Blog Thanks !

Anonymous said...

how to get user email from api?

Omar said...

I got the following error

The remote server returned an error: (407) Proxy Authentication Required.

what is the problem ???

Meenakshi said...

It gives error
remote server returned error:(401)Unauthorized)

safa ismail said...

It gives error
remote server returned error:(401)Unauthorized)

Suranga said...

Follow "R koyee" comment above. It worked for me. http to https. Nice work Suresh.

Anonymous said...

Hi,

Without login in twitter,posible to get tweet information using email addredd in asp.net.

My Requirement is below:
with the use of email address i want to show user profile details & user tweet in my web application.

I create application in twitter for getting api key.

but every time need to login with application.it is not good for me.

So please any idea about how to get those information without login.

Ravi Lamba said...

this code is not working.its gives me error 401
can u help me??what is the procedure to remove the error

public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";

try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;//ih this line error is showed error 401.
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}

return responseData;
}

Anonymous said...

Hi,
Code is working fine for me and I am getting data from twitter. But if I refresh the page, its goes to error 401. Any idea?

DeatK said...

i get 401 unauthorized too
and i used https as suggested by R koyee
but it still does not works...

omprakash kurmi said...

The remote server returned an error: (401) Unauthorized.

not return and retrieve the TokenSecret.

omprakash kurmi said...

url = "https://api.twitter.com/1.1/account/verify_credentials.json";
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);


The remote server returned an error: (401) Bad Request.

omprakash kurmi said...

good blogs suresh,can you tell me how to find the email address of twitter user along with above information

change the following Url to this.

http://api.twitter.com/1/account/verify_credentials.xml

Anonymous said...

Thanks
R koyee,
your suggestion helps me alot.
problem of getting 401 error is solved

Anonymous said...

Thanks, It was very helpful, I have a doubt, I have my App login so I offer the user to log in with Twitter or Facebook. After the user logs in, I compare user data with my App user data. But in order to do this, I need the user Email in order to compare both data. How can I do that if Twitter does not retrieve email? thanks

Narendra babu said...

The below code is not working for me........

Dim responseReader As StreamReader = Nothing
Dim responseData As String = ""
Try
webRequest.Credentials = CredentialCache.DefaultCredentials
responseReader = New StreamReader(webRequest.GetResponse().GetResponseStream())
responseData = responseReader.ReadToEnd()
Catch////in this line error is showed error 401.
Throw
Finally
webRequest.GetResponse().GetResponseStream().Close()
responseReader.Close()
responseReader = Nothing
End Try

Return responseData

Anonymous said...

it posibile get email

email = node["email"].InnerText;???????

Miha said...

You have to set value _callBackUrl = "oob" for desktop version (you would get this message if you call parsed URL (WebRequest function) in your browser). Also use "R koyee" advice for url-s.

avnish kumar singh said...

this code is not working properly please me sir
i got error no 401
and i don't understand what is the meaning of that error plz help and get back to solution as soon possible

error:
(The remote server returned an error: (401) Unauthorized.)

Mayank Sharma said...

I have an Error "The remote server returned an error: (410) Gone" from last 4/5 days.

shraddha shilimkar said...

I have an Error "The remote server returned an error: (410) Gone" ...........m not getting how to solve these error

Anonymous said...

Hello,
I want to post the twit to twitter from my ASP.NET application. so please help me

Nirmal Nagarajan said...

Im getting this error plzzz help...
The remote server returned an error: (401) Unauthorized.

Tomi said...

yup unautorized because we cant get the calback url
maybe you can try the oob version. with autentication code. give it a try download it from https://github.com/raidenz/twitteroauth

Anonymous said...

Hello Sir, It return on my website url with this values "twitter.aspx?oauth_token=TkCDA6rtzr2FD2b8EVmHLR0HN8poqA&oauth_verifier=pQJIWdp7S02QKvrWPDEpKU5FAoxsbTRk"

but it not show the value, it gives an error 401

Nirmal Nagarajan said...

I cant get yo ... I am struggling in this part ... Plzzz can any one help me ... Where is the Author Suresh ... Help me developers ...

Anonymous said...

1.how to retrieve username not getting
2.not going in this function
private void GetUserDetailsFromTwitter()
{
if (Request["oauth_token"] != null & Request["oauth_verifier"] != null)
{
imgTwitter.Visible = false;
tbleTwitInfo.Visible = true;
var oAuth = new oAuthTwitter();
//Get the access token and secret.
oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]);
if (oAuth.TokenSecret.Length > 0)
{
//We now have the credentials, so make a call to the Twitter API.
url = "http://api.twitter.com/1/account/verify_credentials.xml";
xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);


XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
XmlNodeList xmlList = xmldoc.SelectNodes("");
foreach (XmlNode node in xmlList)
{
name = node["name"].InnerText;
username = node["screen_name"].InnerText;
profileImage = node["profile_image_url"].InnerText;
followersCount = node["followers_count"].InnerText;
noOfTweets = node["statuses_count"].InnerText;
recentTweet = node["status"]["text"].InnerText;
}
}
}
}

Anonymous said...

plz help how to retrieve the username in twitter

Sneha Dohale said...

Getting error that OAuthBase could not found

lalan.project11 said...

this erroe display
han can remove
The remote server returned an error: (401) Unauthorized.

Anonymous said...

I have a 401 error too, is someone manage to use this code?

Anonymous said...

I have a 401 error too

Anonymous said...

can any one help out me to resolve the error of 401
its not working its working on localhost
but on server its giving 401 error

rajeev said...

this code is not working.its gives me error 401
can u help me??what is the procedure to remove the error

public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";

try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;//ih this line error is showed error 401.
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}

return responseData;
}

rajeev said...

please change these code in oAuthtwitter.cs as
change http as https....
public const string REQUEST_TOKEN = "https://api.twitter.com/oauth/request_token";
public const string AUTHORIZE = "https://api.twitter.com/oauth/authorize";
public const string ACCESS_TOKEN = "https://api.twitter.com/oauth/access_token";
private string _callBackUrl = "http://www.yoursite.com";// your call back url


401 error wil be cleared..

Kunal Patel said...

how can i get E-mail ID in this application ????

Anonymous said...

How to add reference of oauthexample in project means using oAuthExample; is giving error.

Shekhar Shete MCTS said...

Great @rajeev really it worked for me...! :) thanks a lot!

soumya said...

Hi,
In my MVC website , i want to display 10 latest tweets to the website. How can i do it?

Hari said...

var oAuth = new oAuthTwitter();
error:. namespace doesnt exist.
give the library name

Shekhar Shete MCTS said...

Gives Error:
The remote server returned an error: (401) Unauthorized.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (401) Unauthorized.

Source Error:

Line 295: finally
Line 296: {
Line 297: webRequest.GetResponse().GetResponseStream().Close();
Line 298: responseReader.Close();
Line 299: responseReader = null;

Source File: d:\Shekhar Docs\OpenAuthLogins\App_Code\oAuthTwitter.cs Line: 297

Please Help...!

www.shekharshetemcts.wordpress.com

lavanyan nalluri said...

hooo really thanks...Lavanya

babita said...

Even i have downloaded the code its giving me error :{"The remote server returned an error: (401) Unauthorized."} pls help me out

rimjhim bothra said...

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (401) Unauthorized.

Source Error:


Line 294: finally
Line 295: {
Line 296: webRequest.GetResponse().GetResponseStream().Close();
Line 297: responseReader.Close();
Line 298: responseReader = null;

how to handle this error please help me

Anonymous said...

Thanks for sharing your twitter experience with us. It really works for me.
Regarding getting Email ID, I followed https://dev.twitter.com/discussions/4019 link, the twitter employee clearly mention that "The API won't return an email address" which makes no sense. ;)

Thanks!
Ashish Narnoli

Hu Shien Tan said...

Thanks for the valuable sharing. I followed through every discussion post here. Made corrections to the new URL release by twitter, applied JSON etc, and finally got it working.

Gowtham said...

thanks...but
i have a below error
Sorry, the page you were looking for in this blog does not exist.

umit sener said...

I could not download the file

Kimkwan Lau said...

Thanks for coding.
But I have below error.
The remote server returned an error: (401) Unauthorized.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (401) Unauthorized.

Source Error:


Line 294: finally
Line 295: {
Line 296: webRequest.GetResponse().GetResponseStream().Close();
Line 297: responseReader.Close();
Line 298: responseReader = null;

piya p said...

Hi ,
nice blog but
Response.Redirect(oAuth.AuthorizationLinkGet()); giving runtime error that url can not be null.
and another problem is how to get _oauthVerifier value?
because in my app on twitter I am not getting
Please help me
Thanx..

Anonymous said...

An exception of type 'System.Net.WebException' occurred in App_Code.ancmcf5w.dll but was not handled in user code

Additional information: The remote server returned an error: (401) Unauthorized.

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.