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

47 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

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.