Wednesday, August 8, 2012


Asp.net integrate Facebook login authentication to website

Saturday, April 21, 2012 
Introduction: 

In this article I will explain how to integrate facebook login button to website in asp.net and 
how to create application in facebook.

Description: 
  
In previous post I explained many articles relating to 
Asp.net, JQuery, and SQLServer etc. Now I will explain how to allow users to login with facebook accounts in website using asp.net.

Before implement facebook login authentication we need to create the facebook application for that open this link http://developers.facebook.com/setup/ once open that will display window like this

 
In this enter Application Name and click Continue here App Namespace and web hosting both are optional. After enter details and click Continue to display Security Check required screen like this

Enter security text and click submit button once we click it will create application in facebook that would be like this 

Once our app created on facebook that will be like as shown above image now we can change logo of our app and icon of our application. After that we need to add Site URL, Canvas URL that would be the url of your site (Ex: http://aspdotnet-suresh.com) which site you are going to integrated login button. Actually facebook has stopped 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

After we made all the changes that would be like this 

Once you entered all the details click save changes button. Now create new application using visual studio and write following code aspx page

<html>
<head>
<title>Facebook Login Authentication Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// Load the SDK Asynchronously
(function(d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));

// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId: '198191300293654'// App ID
channelUrl: '//' + window.location.hostname + '/channel'// Path to your Channel File
status: true// check login status
cookie: true// enable cookies to allow the server to access the session
xfbml: true  // parse XFBML
});

// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange'function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me'function(me) {
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function() { FB.logout(function() { window.location.reload(); }); });
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">

<div class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login with Facebook</div>
</div>
<div id="auth-loggedin" style="displaynone">
Hi, <span id="auth-displayname"></span>(<a href="#" id="auth-logoutlink">logout</a>)
</div>
</div>
</body>
</html>
If you observe header section I added one script file that is used to handle click function using JQuery and in body I written another script in that

FB.init: This function is used to set authentication statuses.

FB.apiThis function is used to get authenticated user details.
In above code you need to make small modification that is need to give your appId in FB.init function (appId: ‘YOUR APP ID’).

(Note: Script function should be under <body> tag only)

 Now run your application and check the output that would be like this

Demo

Tuesday, August 7, 2012


Add twitter login authentication to website in asp.net

Monday, 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 linkhttps://dev.twitter.com/apps/new  once open that will display window like this


Once app page opened enter Application Name, Description, website (Ex: http://anilreddymca.blogspot.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://anilreddymca.blogspot.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