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.
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
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. |
|||
|
|||
94 comments :
INDEED YOUR THE BEST...
Thank you very much,but have can I get the user mail address?
hi,
excellent blog .
thanks ,
Ajay
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?
best one yarrr thank u....
thank u but how to get followers/following users images using asp.net
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
Hi...But how to get other details like firstname,lastname,email,city,state etc....
32
Hi sureshbhai i got this error on return url,
The remote server returned an error: (404) Not Found.
Once i click on Authrize app im getting a window with pin number and it ask me to type it in my website
Hey Suresh good example, I did the same thing and am getting a 404 exception. Not sure whats wrong though..
Again thanks sir...
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.
Change the foolwing url with
http://api.twitter.com/1/account/verify_credentials.xml
it worked
Really nice article
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:
Pls reflesh the source code links
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.
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 ...
https://dev.twitter.com/apps/new
you can get <add key="consumerKey"
<add key="consumerSecret"
on this link
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 ?
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"]);
}
Hello,
It doesn't work it gives error 401 ... Any solutions,Please?
Regards
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 .
hey,It gives me error :
The remote server returned an error: (401) Unauthorized.
Nice Blog Thanks !
how to get user email from api?
I got the following error
The remote server returned an error: (407) Proxy Authentication Required.
what is the problem ???
It gives error
remote server returned error:(401)Unauthorized)
It gives error
remote server returned error:(401)Unauthorized)
Follow "R koyee" comment above. It worked for me. http to https. Nice work Suresh.
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.
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;
}
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?
i get 401 unauthorized too
and i used https as suggested by R koyee
but it still does not works...
The remote server returned an error: (401) Unauthorized.
not return and retrieve the TokenSecret.
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.
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
Thanks
R koyee,
your suggestion helps me alot.
problem of getting 401 error is solved
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
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
it posibile get email
email = node["email"].InnerText;???????
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.
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.)
I have an Error "The remote server returned an error: (410) Gone" from last 4/5 days.
I have an Error "The remote server returned an error: (410) Gone" ...........m not getting how to solve these error
Hello,
I want to post the twit to twitter from my ASP.NET application. so please help me
Im getting this error plzzz help...
The remote server returned an error: (401) Unauthorized.
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
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
I cant get yo ... I am struggling in this part ... Plzzz can any one help me ... Where is the Author Suresh ... Help me developers ...
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;
}
}
}
}
plz help how to retrieve the username in twitter
Getting error that OAuthBase could not found
this erroe display
han can remove
The remote server returned an error: (401) Unauthorized.
I have a 401 error too, is someone manage to use this code?
I have a 401 error too
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
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;
}
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..
how can i get E-mail ID in this application ????
How to add reference of oauthexample in project means using oAuthExample; is giving error.
Great @rajeev really it worked for me...! :) thanks a lot!
Hi,
In my MVC website , i want to display 10 latest tweets to the website. How can i do it?
var oAuth = new oAuthTwitter();
error:. namespace doesnt exist.
give the library name
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
hooo really thanks...Lavanya
Even i have downloaded the code its giving me error :{"The remote server returned an error: (401) Unauthorized."} pls help me out
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
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
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.
thanks...but
i have a below error
Sorry, the page you were looking for in this blog does not exist.
I could not download the file
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;
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..
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.
i am getting an error , the type or namespace oAuthTwitter does not found
thanks for this great article :) but unfortunately this code is not running now. After downloading the sample code and run the application I'm always get the message of "The remote server returned an error: (401) Unauthorized." so please any help would be appreciated
[WebException: The remote server returned an error: (401) Unauthorized.]
System.Net.HttpWebRequest.GetResponse() +6542104
oAuthExample.oAuthTwitter.WebResponseGet(HttpWebRequest webRequest) +137
oAuthExample.oAuthTwitter.WebRequest(Method method, String url, String postData) +233
oAuthExample.oAuthTwitter.oAuthWebRequest(Method method, String url, String postData) +667
oAuthExample.oAuthTwitter.AuthorizationLinkGet() +26
zoufin.azurewebsites.net.TwitterAuthentication.imgTwitter_Click(Object sender, ImageClickEventArgs e) +83
System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +115
System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +124
System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
sir i m Receiving Below Errors...kindly look it sir
Server Error in '/' Application.
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;
i use @Rajeev solution , still not working, get this error after authorize twitter. The remote server returned an error: (404) Not Found.
Line 300: finally
Line 301: {
*** red here Line 302: webRequest.GetResponse().GetResponseStream().Close();
Line 303: responseReader.Close();
Line 304: responseReader = null;
any help ?
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ITS WORKING FOR ME. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! :)
Twitter has changed its links. Here are the changes to be made.
(1) INSIDE oAuthTwitter.cs
- Change the link to this: (from line 23)
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";
(2) INSIDE TwitterAuthentication.aspx.cs
(a) Put proper url callback: (line 61)
oAuth.CallBackUrl = ""; //put your callback url inside the quotation.
(b) Use json call with proper version(1.1) (xml response no longer supported) : (line 34)
//We now have the credentials, so make a call to the Twitter API.
url = "https://api.twitter.com/1.1/account/verify_credentials.json";
//Example to use json response
var jsonResult = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);
// Newtonsoft deserialize Method ; for this include
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
var jsonDe = JsonConvert.DeserializeObject(jsonResult);
id = jsonDe.id_str;
name = jsonDe.name;
username = jsonDe.screen_name;
profileImage = jsonDe.profile_image_url;
sir any method for login with twitter using javascript???
hello,Its Give me error while return call back from twitter "Additional information: The remote server returned an error: (404) Not Found."
When i am click on authorize button then it gives Bad Request - Invalid Hostname HTTP Error 400. The request hostname is invalid. error
please help me
twitter login to website in asp.net possible for local site?if possible please sir give detail as soon as possible.
thank u
Note: Only a member of this blog may post a comment.