tag:blogger.com,1999:blog-26148414789118446042024-03-28T22:44:43.154-07:00The .Net BlogAnonymoushttp://www.blogger.com/profile/15420290858166123413noreply@blogger.comBlogger3125tag:blogger.com,1999:blog-2614841478911844604.post-53717539268272677152012-08-31T09:05:00.003-07:002012-09-01T09:56:53.840-07:00Implement Facebook Login with OpenID Selector in MVC3<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
In My last <a href="http://srkrathore.blogspot.com/2012/08/implement-facebook-login-with-openid.html#more" target="_blank">post</a>, I explained how we can implement Facebook login with OpenId selector tool. In this post I will explain you how we can use that tool in an ASP.NET MVC3 application.<br />
<br />
<a name='more'></a><br />
<br />
1- Open Visual Studio 2010 go to File > New > Project > Web > ASP.NET MVC 3 Application:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLSfFpC5lGp7bhRjB-Mt0OqRJkjT6CRkxXtiC422XnR2AGRkXjGfAiIHziAKHMAD8nQLMXJ4SpbxNx1kzpoVcw731oZen-jD51sDZTq4Xnoq-9tDVLAe75CYqhahpVxfFDGj22TiNDRPk/s1600/CreateProject.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="221" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLSfFpC5lGp7bhRjB-Mt0OqRJkjT6CRkxXtiC422XnR2AGRkXjGfAiIHziAKHMAD8nQLMXJ4SpbxNx1kzpoVcw731oZen-jD51sDZTq4Xnoq-9tDVLAe75CYqhahpVxfFDGj22TiNDRPk/s320/CreateProject.PNG" width="320" /></a></div>
<br />
then Choose Internet Application be sure to have Razor as your View engine and Click OK:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe625bHgHklv_B14MaguDdEY4tDSL59EpsOfHZwu_pAvVPEm2ewyRAETK5XMDTuL3b18PIPzcfM2wmwwqsun-5Nd6xx6C3B-rrK5lZOYIBLBwXkavY8UVKhQNj2CTMyRBu6UR3pP5XElg/s1600/SelectRazor.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="293" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe625bHgHklv_B14MaguDdEY4tDSL59EpsOfHZwu_pAvVPEm2ewyRAETK5XMDTuL3b18PIPzcfM2wmwwqsun-5Nd6xx6C3B-rrK5lZOYIBLBwXkavY8UVKhQNj2CTMyRBu6UR3pP5XElg/s320/SelectRazor.PNG" width="320" /></a></div>
2- Download <a href="http://www.dotnetopenauth.net/" target="_blank">DotNetOpenAuth</a> dll and <a href="https://docs.google.com/open?id=0B_egqeuMTSYnWl9JYlpCc1A5ZTg" target="_blank">Updated OpenID Selector</a> files that we will use. <br />
A- Add the DotNetOpenAuth.dll to references in your site.<br />
B- Copy all contents of openid-selector\css folder to the 'Content' folder .<br />
C- Copy images, images.large, images.small folders to the site 'Content' folder.<br />
D- Copy openid-jquery.js, openid-en.js files from openid-selector\js folder to 'Scripts' folder<br />
<br />
Your Solution Explorer will look like this (See Highlighted Portion) :<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguRGa5SX7YHLyLURKVGU1wWdXRmxDZBZ2UU7eGfnM8wUiesrrhc5VljIdDs1lxyTxXyXzH5kkWKiggVhCT7ZZ6jKqd_NlwCLmZGaE1ESWOCXXdpydEgglcOTvxI6waaNcyOij5PmBqxkQ/s1600/SEScripts.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguRGa5SX7YHLyLURKVGU1wWdXRmxDZBZ2UU7eGfnM8wUiesrrhc5VljIdDs1lxyTxXyXzH5kkWKiggVhCT7ZZ6jKqd_NlwCLmZGaE1ESWOCXXdpydEgglcOTvxI6waaNcyOij5PmBqxkQ/s320/SEScripts.PNG" style="cursor: move;" width="107" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinNrzgN-Y9wC6dhIuH42wOU05jHZqLoNg0qzm_LjcZEhiIk8Jr7lcboYGRJVOvhSmQCvDCVS_L62WdHvVvmpmb-dURuX5499EGDCcXXPyK97Z6WjB7eEWR1__-tW0pjuCqz0NmDIkPa6s/s1600/SolutionExplorDonet.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinNrzgN-Y9wC6dhIuH42wOU05jHZqLoNg0qzm_LjcZEhiIk8Jr7lcboYGRJVOvhSmQCvDCVS_L62WdHvVvmpmb-dURuX5499EGDCcXXPyK97Z6WjB7eEWR1__-tW0pjuCqz0NmDIkPa6s/s320/SolutionExplorDonet.PNG" width="106" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<br />
3- Go to Views > Shared > _Layout.cshtml and replace the
<head> with this new head with new styles and
scripts:<br />
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code><head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Content/openid-shadow.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/openid.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/openid-jquery.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/openid-en.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"> </script>
<script type="text/javascript">
$(document).ready(function () {
openid.init('openid_identifier');
});
</script>
</head>
</code></pre>
<br />
<pre class="csharpcode"><span class="kwrd"><span style="color: black;">4- Go to Models > AccountModels.cs , navigate to <span style="color: blue;">public class</span> LogOnModel</span></span></pre>
<pre class="csharpcode"><span class="kwrd"> <span style="color: black;">and Add <span style="color: blue;">OpenID</span> attribute that we will use it to hold the returned OpenID from OpenID-Selector</span></span></pre>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;"> your class will look like this:</span></span></pre>
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> public class LogOnModel
{
[Display(Name = "OpenID")]
public string OpenID { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
</code></pre>
<br />
<pre class="csharpcode"><span class="kwrd"><span style="color: black;">5- </span></span><span class="kwrd"><span style="color: black;">Go to Models > AccountModels.cs and Add following class to it:</span></span></pre>
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> public class UserDetailsModel
{
public string OpenID { get; set; }
public string ProviderUrl { get; set; }
public string FriendlyIdentifier { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Dob { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
}
</code></pre>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;"> </span></span><span class="kwrd"><span style="color: black;"> </span></span></pre>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;">6- go to Views > Account > LogOn.cshtml </span></span><span class="kwrd"><span style="color: black;">replace all the markup with this one, This will</span></span></pre>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;"> integrate updated OpenID-Selector to LogOn View:</span></span><span class="kwrd"><span style="color: black;"> </span></span></pre>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;"> </span></span></pre>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;"> </span></span></pre>
</div>
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>@model FBOpenIDMVC3.Models.LogOnModel
@{
ViewBag.Title = "Log On";
}
<h2>
Log On</h2>
<p>
Please enter your username and password. @Html.ActionLink("Register", "Register")
if you don't have an account.
</p>
<script type="text/javascript">
$(document).ready(function () {
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: '188220747944294', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
scope: 'id,name,first_name,last_name,gender,email',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
};
});
/*This Method will be invoked on lick on Facebook button*/
function FBLogin() {
FB.login(FBCallBack);
}
function FBCallBack(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me?fields=id,name,first_name,last_name,gender,email,birthday', function (userDetail) {
if (userDetail.name) {
var url = '@Url.Action("ShowUserDetails", "Account", new { OpenID = "_id_", FriendlyIdentifier = "_id_", FirstName = "_first_", LastName = "_last_", Dob = "_birthday_", Gender = "_gender_", Email = "_email_" })';
url = url.replace('_id_', userDetail.id);
url = url.replace('_id_', userDetail.id);
url = url.replace('_first_', userDetail.first_name);
url = url.replace('_last_', userDetail.last_name);
url = url.replace('_birthday_', userDetail.birthday);
url = url.replace('_gender_', userDetail.gender);
url = url.replace('_email_', userDetail.email);
window.location.href = url;
}
});
}
}
</script>
<form action="Authenticate?ReturnUrl=@HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"])" method="post" id="openid_form">
<input type="hidden" name="action" value="verify" />
<div>
<fieldset>
<legend>Login using OpenID</legend>
<div class="openid_choice">
<p>
Please click your account provider:</p>
<div id="openid_btns">
</div>
</div>
<div id="openid_input_area">
@Html.TextBox("openid_identifier")
<input type="submit" value="Log On" />
</div>
<noscript>
<p>
OpenID is service that allows you to log-on to many different websites using a single
indentity. Find out <a href="http://openid.net/what/">more about OpenID</a> and
<a href="http://openid.net/get/">how to get an OpenID enabled account</a>.</p>
</noscript>
<div>
@if (Model != null)
{
if (String.IsNullOrEmpty(Model.UserName))
{
<div class="editor-label">
@Html.LabelFor(model => model.OpenID)
</div>
<div class="editor-field">
@Html.DisplayFor(model => model.OpenID)
</div>
<p class="button">
@Html.ActionLink("New User ,Register", "Register", new { OpenID = Model.OpenID })
</p>
}
else
{
//user exist
<p class="buttonGreen">
<a href="@Url.Action("Index", "Home")">Welcome , @Model.UserName, Continue..." </a>
</p>
}
}
</div>
</fieldset>
</div>
</form>
@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
@using (Html.BeginForm())
{
<div>
<fieldset>
<legend>Or Login Normally</legend>
<div class="editor-label">
@Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
<p >
<input type="submit" value="Log On" />
</p>
</fieldset>
</div>
}
</code></pre>
7- Update the value of <i><b>img_path</b></i> in <i><b>openid-jquery.js</b></i> to <i><b>'../Content/images/'</b></i><br />
8- Now let us run the project , then click the [Log On] link , you will get like this page:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHKndow4q6-7AM2yQ2mBYAYWYpQjzl5P33caNNHHe7wzjxeqpxqfqooLHHWd38SgVWn4Ck69N12JblWhEHqaeHIS2PFtluCixm8lFyFgw3UV3UR80QhlKIO6XAT176YyifgU5l3E6N6lw/s1600/MainPage.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="247" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHKndow4q6-7AM2yQ2mBYAYWYpQjzl5P33caNNHHe7wzjxeqpxqfqooLHHWd38SgVWn4Ck69N12JblWhEHqaeHIS2PFtluCixm8lFyFgw3UV3UR80QhlKIO6XAT176YyifgU5l3E6N6lw/s320/MainPage.PNG" width="320" /></a></div>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;">9- Now to implement Open ID using DotnetOpenAuth, Go to Controllers > </span></span></pre>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;">AccountController.cs and Add these using:</span></span></pre>
<pre class="csharpcode"><span class="kwrd"><span style="color: black;"> </span></span></pre>
</div>
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
</code></pre>
Then Add the following code to AccountController.cs:
<br />
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> private static OpenIdRelyingParty openid = new OpenIdRelyingParty();
[ValidateInput(false)]
public ActionResult Authenticate(string returnUrl)
{
var response = openid.GetResponse();
if (response == null)
{
//Let us submit the request to OpenID provider
Identifier id;
if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
{
try
{
var request = openid.CreateRequest(Request.Form["openid_identifier"]);
var fetch = new FetchRequest();
fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.BirthDate.WholeBirthDate, true));
fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Person.Gender, true));
fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.First, true));
fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.Last, true));
request.AddExtension(fetch);
return request.RedirectingResponse.AsActionResult();
}
catch (ProtocolException ex)
{
ViewBag.Message = ex.Message;
return View("LogOn");
}
}
ViewBag.Message = "Invalid identifier";
return View("LogOn");
}
//Let us check the response
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
var fetch = response.GetExtension<FetchResponse>();
var sFirstName = "";
var sEmail = "";
var sLastName = "";
var sGender = "";
var sDob = "";
if (fetch != null)
{
foreach (var vAtrrib in fetch.Attributes)
{
switch (vAtrrib.TypeUri)
{
case WellKnownAttributes.Name.First:
var firstNames = fetch.Attributes[WellKnownAttributes.Name.First].Values;
sFirstName = firstNames.Count > 0 ? firstNames[0] : null;
break;
case WellKnownAttributes.Contact.Email:
var emailAddresses = fetch.Attributes[WellKnownAttributes.Contact.Email].Values;
sEmail = emailAddresses.Count > 0 ? emailAddresses[0] : null;
break;
case WellKnownAttributes.Name.Last:
var lastNames = fetch.Attributes[WellKnownAttributes.Name.Last].Values;
sLastName = lastNames.Count > 0 ? lastNames[0] : null;
break;
case WellKnownAttributes.Person.Gender:
var genders = fetch.Attributes[WellKnownAttributes.Person.Gender].Values;
sGender = genders.Count > 0 ? genders[0] : null;
break;
case WellKnownAttributes.BirthDate.WholeBirthDate:
var doBs = fetch.Attributes[WellKnownAttributes.BirthDate.WholeBirthDate].Values;
sDob = doBs.Count > 0 ? doBs[0] : null;
break;
}
}
}
var sFriendlyLogin = response.FriendlyIdentifierForDisplay;
var lm = new UserDetailsModel
{
OpenID = response.ClaimedIdentifier,
FriendlyIdentifier = sFriendlyLogin,
FirstName = sFirstName,
LastName = sLastName,
Dob = sDob,
Gender = sGender,
Email = sEmail
};
FormsService.SignIn(sEmail, false);
return View("ShowUserDetails", lm);
case AuthenticationStatus.Canceled:
ViewBag.Message = "Canceled at provider";
return View("LogOn");
case AuthenticationStatus.Failed:
ViewBag.Message = response.Exception.Message;
return View("LogOn");
}
return new EmptyResult();
}
public ActionResult ShowUserDetails(UserDetailsModel objUserDetails)
{
return View(objUserDetails);
}
[HttpPost]
public ActionResult ShowUserDetails(string OpenID, string FriendlyIdentifier, string FirstName, string LastName, string Dob, string Gender, string Email)
{
var objUserDetails = new UserDetailsModel()
{
OpenID = OpenID,
FriendlyIdentifier = FriendlyIdentifier,
FirstName = FirstName,
LastName = LastName,
Dob = Dob,
Gender = Gender,
Email = Email,
};
return View(objUserDetails);
}
</code></pre>
10 - Right Click on Views--> Accounts and Click Add-->View to add new view like this:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBtmryb7SL2h-IrUVfl_Zit7cNGvl77kggqYG4_Dn7DdWjaFGt-5uYckZC9e87DlKkSRI-PEwI0zxbJBRWXEjWoNB2P4ZK_TF4FR6iY6LWBICh3rUFbfjkDOa680WVZEk8d8ly2HcTE_c/s1600/ShowDetails.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBtmryb7SL2h-IrUVfl_Zit7cNGvl77kggqYG4_Dn7DdWjaFGt-5uYckZC9e87DlKkSRI-PEwI0zxbJBRWXEjWoNB2P4ZK_TF4FR6iY6LWBICh3rUFbfjkDOa680WVZEk8d8ly2HcTE_c/s320/ShowDetails.PNG" width="317" /></a></div>
11- Add following code in this View:</div>
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> public class UserDetailsModel
{
public string OpenID { get; set; }
public string ProviderUrl { get; set; }
public string FriendlyIdentifier { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Dob { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
}
</code></pre>
12- Now run the project click [Log On] link and click a provider like Google
it may ask you to sign in or ask you to allow access to your information
you will get a page like this :<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTqbeA8AUxxh6N1EQQ-iA8XpvDuM2VT536YSi77_UFX_BsPYpBUrZrhp5lTgeqcPC-VJhcSRIfKageh556ImfAY3SzcBISYCIZ7AWDbXe-DZHiX-532Ta66My-KfutrrcgGd_8JhWoHh4/s1600/FinalPage.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="247" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTqbeA8AUxxh6N1EQQ-iA8XpvDuM2VT536YSi77_UFX_BsPYpBUrZrhp5lTgeqcPC-VJhcSRIfKageh556ImfAY3SzcBISYCIZ7AWDbXe-DZHiX-532Ta66My-KfutrrcgGd_8JhWoHh4/s320/FinalPage.PNG" width="320" /></a></div>
Congratulations , now you had integrated OpenID login with facebook login to your project.<br />
<br />
<a href="https://docs.google.com/open?id=0B_egqeuMTSYneVpiLXpKa01Kd3M" target="_blank">Download Code from here</a><br />
<br />
<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/15420290858166123413noreply@blogger.com12tag:blogger.com,1999:blog-2614841478911844604.post-66946645595714251462012-08-30T20:36:00.001-07:002012-08-31T04:43:16.999-07:00Implement Facebook login with OpenID Selector<div dir="ltr" style="text-align: left;" trbidi="on">
OpenID selector (<a href="http://code.google.com/p/openid-selector/" target="_blank">Get from here</a>) created by google is a very good control to implement OpenID in your application, but extending that control to use Facebook login is quite tricky as the documentation given there for it is quite confusing. So I will provide you step by step guide here on how to implement Facebook login in OpenID selector, we will be updating the OpenID selector sample HTML ('demo.html' file) itself.<br />
<br />
First we have to include the Facbook button with it's logo in the openid selector large buttons, to do that we will have to change 'openid-en.js' and 'openid-jquery.js' file present in 'js' folder. <br />
<br />
<br />
<a name='more'></a><br />
<h4 style="text-align: left;">
Changes in 'openid-en.js' :</h4>
This file contains two enumeration variables 'providers_large' for displaying larger buttons and 'providers_small' for displaying smaller buttons. Depending upon your choice where you want to display the Facebook button add the following code in any of the provider enumerator.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> facebook : {
name: 'Facebook',
url: 'javascript:FBLogin();'
},
</code></pre>
<br />
<br />
<span style="font-family: "Courier New", Courier, monospace;">
</span>
This change will make sure that when user clicks on Facebook icon, it will invoke the 'FBLogin' JavaScript code which we will write in 'demo.html' file.<br />
<h4 style="text-align: left;">
Changes in 'openid-jquery.js':</h4>
This file is responsible for the whole working of OpenId control. Following are the changes required in this file in order to implement Facebook button.<br />
<ul style="text-align: left;">
<li>Currently the demo uses one large single image file (openid-providers-en.png in 'images folder') for displaying the buttons present in control. We will have to change the code to create the control using individual images present in 'images.large' and 'images.small' folders. <i>For that change the value of 'no_sprite' from 'false' to 'true'</i></li>
<li>Comment the following code block in '<span style="font-family: "Courier New", Courier, monospace;">submit</span>' method, so that its doesn't invoke the demo alert: </li>
</ul>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
if (openid.demo) {
alert(openid.demo_text + "\r\n" +
document.getElementById(openid.input_id).value);
return false;
}
</code></pre>
<br />
After doing these changes if you open the 'demo.html' you will be able to see the Facebook button in large and small section (wherever you have implemented the change).<br />
<br />
This is how control will look if it is added to large buttons section:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFWP1_YbKO0S3yNAFLtmOe7nwFxANc8bJ9yCr6pPG7EvxJv1BoGkMPqYhW3KW3Pp4JXrsQ-yOLA4QvMu_lAg6RCLIEO0fwZQ-V54-FUppuyYMxMs5PTAZJuVlINeffCcAaf9VHOKiLXPo/s1600/FBLarge.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="208" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFWP1_YbKO0S3yNAFLtmOe7nwFxANc8bJ9yCr6pPG7EvxJv1BoGkMPqYhW3KW3Pp4JXrsQ-yOLA4QvMu_lAg6RCLIEO0fwZQ-V54-FUppuyYMxMs5PTAZJuVlINeffCcAaf9VHOKiLXPo/s320/FBLarge.PNG" width="320" /></a></div>
And this when it is added to small buttons section:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhz2zvSEaLpsgMUF9cfqHPKnHt1jIJB0HVfMtHFsrecaaSSLg0FMj1BFRJx9FzQ5W58yiHcO2KqKew4Q-s2royzZjxImkeSBr4vSeBOqZDiavyATyUMcfTtE_gh0PTw9kFdxDDSTOqwakY/s1600/FBSmall.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="174" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhz2zvSEaLpsgMUF9cfqHPKnHt1jIJB0HVfMtHFsrecaaSSLg0FMj1BFRJx9FzQ5W58yiHcO2KqKew4Q-s2royzZjxImkeSBr4vSeBOqZDiavyATyUMcfTtE_gh0PTw9kFdxDDSTOqwakY/s320/FBSmall.PNG" width="320" /></a></div>
<br />
<h4 style="text-align: left;">
Changes in 'demo.html':</h4>
1) Initialize the Facebook API in the page by copying following code in '$(document).ready' function <br />
of JavaScript.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
FB.init({
appId: 'YOUR_APP_ID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
scope: 'id,name,first_name,last_name,gender,email',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
</code></pre>
<br />
2) Copy following JavaScript methods in Head section:<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>/*This Method will be invoked on lick on Facebook button*/
function FBLogin() {
FB.login(FBCallBack);
}
//Call back method to display results
function FBCallBack(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me?fields=id,name,first_name,last_name,gender,email,birthday', function (userDetail) {
if (userDetail.name) {
var vMessage = 'Hi ' + userDetail.name + ' Your Facebook ID is ' + userDetail.id + ' , Your Birthday is ' + userDetail.birthday + ' and email is ' + userDetail.email;
alert (vMessage);
}
});
}
}
</code></pre>
<span style="font-family: "Courier New", Courier, monospace;"><span style="font-family: inherit; font-size: small;"> </span></span><br />
<br />
<b><i>In order to test this code you must deploy this on any web server and register your website in Facebook (</i></b><a href="http://srkrathore.blogspot.in/2012/08/using-facebook-login-in-aspnet.html" target="_blank"><b><i>See the First section of my this blog.</i></b></a><b><i>).</i></b><br />
<b></b><br />
<a href="https://docs.google.com/open?id=0B_egqeuMTSYnWl9JYlpCc1A5ZTg" target="_blank">Download Code From here</a><br />
<br />
References:<br />
<a href="http://code.google.com/p/openid-selector/" target="_blank">http://code.google.com/p/openid-selector/</a><br />
<br />
<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/15420290858166123413noreply@blogger.com15tag:blogger.com,1999:blog-2614841478911844604.post-51422133706157588322012-08-30T03:49:00.000-07:002012-08-31T05:10:06.249-07:00Using Facebook login in ASP.NET application without any third party library.<div dir="ltr" style="text-align: left;" trbidi="on">
Facebook is extremely popular these days and you will hardly find anyone without Facebook profile, more and more people now want there site to use Facebook authentication in their application, instead of using their own user database to maintain user credentials. In this article I will give you step by step demo on how to integrate Facebook login into you screen.<br />
<br />
<b>Step-1: Register site in Facebook:</b><br />
In order to use Facebook login, <b>you should must have a verified developer account in Facebook</b> (which is very easy to create just login to http://developers.facebook.com using your Facebook credentials and follow the screen instructions) <b>and you must register you website in the form of an App in Facebook</b>.<b><br /></b><br />
<br />
<a name='more'></a><br />
<br />
So lets start with registering your site with Facebook:<br />
1) Open http://developers.facebook.com and login with your Facebook credentials after logging in you will get a screen like this:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiyyaVLwAWvqyIzjjMRINf3Uo8n92BV0Ig7xu514jF5HTH_TAXUJYB9IXYwq83FkOJOUIx8pYb68S1QmAlj4JUXUFo9FuofNtBr2RSPwwhB8GFE6rP02UDvAFMsCpH4XfMv3fC8UrQ2u8/s1600/FBLogin.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="247" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiyyaVLwAWvqyIzjjMRINf3Uo8n92BV0Ig7xu514jF5HTH_TAXUJYB9IXYwq83FkOJOUIx8pYb68S1QmAlj4JUXUFo9FuofNtBr2RSPwwhB8GFE6rP02UDvAFMsCpH4XfMv3fC8UrQ2u8/s320/FBLogin.PNG" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZ9ShQX0pQ-6rYNZdsWjkpc4e0ghyAWWn9HSOqlmXk81i4vfw7d6iw24XU2qYK8EmEFawXXt-VEZB0LWjrfQmBqEGovwQWr72uzeh4T1VTDluF7gIJaXGo0JYfXwTVY923a5-YzV686KE/s1600/CreateNewApp.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"> </a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjkQlgqRzSwCvic7Nao_n8m3VSqL_iB9mdVTN-izn-Qtwx8wBJETNqTd44R03J_RuogNcAoys33dCAq-ZS1t_1T9JO1URD0epvVYK63EAxzQqFXES2iQ2r8UaHT-CO29oiZaMd7NwJIm4/s1600/CreateNewApp.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><br /></a></div>
2) Click on "Build for Websites" link, you will reach to https://developers.facebook.com/docs/guides/web/ , just click on 'Apps' menu Items (the last menu Item from right side), you will reach to https://developers.facebook.com/apps. Click on <a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjkQlgqRzSwCvic7Nao_n8m3VSqL_iB9mdVTN-izn-Qtwx8wBJETNqTd44R03J_RuogNcAoys33dCAq-ZS1t_1T9JO1URD0epvVYK63EAxzQqFXES2iQ2r8UaHT-CO29oiZaMd7NwJIm4/s1600/CreateNewApp.PNG" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjkQlgqRzSwCvic7Nao_n8m3VSqL_iB9mdVTN-izn-Qtwx8wBJETNqTd44R03J_RuogNcAoys33dCAq-ZS1t_1T9JO1URD0epvVYK63EAxzQqFXES2iQ2r8UaHT-CO29oiZaMd7NwJIm4/s1600/CreateNewApp.PNG" /></a> button, you will get following screen.<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBWwwfHizfwLqsHyyu2HhuMrlfmhSHjC9jruZMDan_bm_XyzKoHWyYj3idOMJbILT4pMIJzvn1IS1S9EFStoXepylRldlcIdJhx6ujAdPa_SndLJYS-zCl6kNocV1Jhakbth7TeSLEeKE/s1600/CreateNewApp2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="98" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBWwwfHizfwLqsHyyu2HhuMrlfmhSHjC9jruZMDan_bm_XyzKoHWyYj3idOMJbILT4pMIJzvn1IS1S9EFStoXepylRldlcIdJhx6ujAdPa_SndLJYS-zCl6kNocV1Jhakbth7TeSLEeKE/s320/CreateNewApp2.PNG" width="320" /></a></div>
3) Enter the name of your website in place of App Name, rest of the fields are optional so fill them if you require to use them and click on 'Continue' button. you will be asked to fill a captcha screen and then you will get the summary screen like below screenshot (Just masked the AppID).<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbjK2aOPsx4_pFyzhpi6e2tLwwRswqOZGULSt01tDqnySYQnC7_eK7OTK266-ZbNC1BcMjpdiybtI0D9db6eZ2Ni_KI8WIuZdJy0VudzP26FrczF3X4JiCRMZJmx-h03yfJK21vdUHmHY/s1600/AppSummary.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="247" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbjK2aOPsx4_pFyzhpi6e2tLwwRswqOZGULSt01tDqnySYQnC7_eK7OTK266-ZbNC1BcMjpdiybtI0D9db6eZ2Ni_KI8WIuZdJy0VudzP26FrczF3X4JiCRMZJmx-h03yfJK21vdUHmHY/s320/AppSummary.PNG" width="320" /></a></div>
4) Give the URL of you website/ application Site URL text box of the app summery screen, like below screenshot.I have given localhost address as I will be testing the app from my local build, you will have to give your website URL in this.<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEik-aW10GE_z4yYooTfU2iuZXT9P951OoATVpzgwT1J8JDLMPfkZC4QS_iOVPfePawN_fAsaPS3styve205Ubj4MayKI__oV_B4jIgBQcFNh0UjZdvlV5aW5-OI4ifGzYARts2Bvvkh7FQ/s1600/WebSiteURL.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="247" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEik-aW10GE_z4yYooTfU2iuZXT9P951OoATVpzgwT1J8JDLMPfkZC4QS_iOVPfePawN_fAsaPS3styve205Ubj4MayKI__oV_B4jIgBQcFNh0UjZdvlV5aW5-OI4ifGzYARts2Bvvkh7FQ/s320/WebSiteURL.PNG" width="320" /></a></div>
<br />
<br />
<br />
<br />
Now you are ready to create ASP.Net Web Application, to use Facebook integration.<br />
<br />
<b>Step-2: Create ASP.NET application using Facebook login:</b><br />
1) Open Visual Studio.<br />
2) Select File --> New --> Project/Solution --> 'ASP.NET Empty Application'<br />
3) Now Right Click on Project Name Select Add--> New Item from the pop-up menu and click on 'Web Form' to add Default.Aspx page. (See screenshot).<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-Y8pDK0i9PxCO1g0S3CfPV9QaySQAUkkBRtuJvKLqhTHJ0vDWp9d3mxg89S_lEyqoDxAWxO1mdOxehwnWbEVpCKrCuMFVChctzryCaFO8cCR4fhTceetfdg75ECAUU3GBiFCXftZ3bkY/s1600/AddDefault.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="256" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-Y8pDK0i9PxCO1g0S3CfPV9QaySQAUkkBRtuJvKLqhTHJ0vDWp9d3mxg89S_lEyqoDxAWxO1mdOxehwnWbEVpCKrCuMFVChctzryCaFO8cCR4fhTceetfdg75ECAUU3GBiFCXftZ3bkY/s320/AddDefault.PNG" width="320" /></a></div>
4) Most of the code we will be doing on the HTML code of ASP.NET Page. <br />
5) For using Facebook login, we will have to use Facebook JavaScript SDK. There are three ways of using it:<br />
a) Load the JavaScript SDK asynchronously. <br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> <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#xfbml=1";
ref.parentNode.insertBefore(js, ref);
} (document));
</script>
</code></pre>
<br />
<br />
b) Load the JavaScript SDK synchronously<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> <script src=https://connect.facebook.net/en_US/all.js type="text/javascript"></script>
</code></pre>
<span style="font-size: x-small;"><span style="font-family: Consolas;"><br /><span style="color: blue;"><span style="color: blue;"><span style="color: blue;"></span></span></span></span></span>
c) Download the SDK JavaScript file in your local project folder and use it from there. Implemented in 'Default.aspx' of solution.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> <script src="scripts/all.js" type="text/javascript"></script>
</code></pre>
<br />
<br />
6) We will also require <a href="http://www.jquery.com/" target="_blank">jquery</a> for initializing the library. so copy following code in header section of the page. <span style="font-family: Consolas; font-size: x-small;"></span>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code><script src="scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="scripts/all.js" type="text/javascript"></script>
</code></pre>
<br />
<span style="font-family: Consolas; font-size: x-small;"></span><br />
<span style="font-family: Consolas; font-size: x-small;"><span style="font-family: Consolas; font-size: x-small;"></span></span>7) Now to initialize the Facebook SDK copy following code in a new script section :
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
$("document").ready(function () {
// Initialize the SDK upon load
FB.init({
appId: 'YOUR_APP_ID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
scope: 'id,name,gender,user_birthday,email', // This to get the user details back from Facebook
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', OnLogin);
});
</code></pre>
Here YOUR_APP_ID will be the App Id you will get from the Facebook App.<br />
<br />
8) Also copy the following code after Above code in to get the response back and fill the values.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
// This method will be called after the user login into facebook.
function OnLogin(response) {
if (response.authResponse) {
FB.api('/me?fields=id,name,gender,email,birthday', LoadValues);
}
}
//This method will load the values to the labels
function LoadValues (me) {
if (me.name) {
document.getElementById('displayname').innerHTML = me.name;
document.getElementById('FBId').innerHTML = me.id;
document.getElementById('DisplayEmail').innerHTML = me.email;
document.getElementById('Gender').innerHTML = me.gender;
document.getElementById('DOB').innerHTML = me.birthday;
document.getElementById('auth-loggedin').style.display = 'block';
}
}
</code></pre>
9) Copy following code in the Body tag of the Page.
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code> <div id="fb-root"></div> <!-- This initializes the FB controls-->
<div class="fb-login-button" autologoutlink="true" scope="user_birthday,email" >
Login with Facebook
</div> <!-- FB Login Button -->
<!-- Details -->
<div id="auth-status">
<div id="auth-loggedin" style="display: none">
Hi, <span id="displayname"></span><br/>
Your Facebook ID : <span id="FBId"></span><br/>
Your Email : <span id="DisplayEmail"></span><br/>
Your Sex:, <span id="Gender"></span><br/>
Your Date of Birth :, <span id="DOB"></span><br/>
</div>
</div>
</code></pre>
10) Your application is ready now, execute the application.<br />
<br />
In this blog we have learned how to register an application in Facebook and the use that application for Facebook authentication in our ASP.NET website/application. Using this the user of your web site/application will be free from the hassle of registering and entering their details again if they have Facebook Id they can use that to login.<br />
<br />
<a href="https://docs.google.com/open?id=0B_egqeuMTSYnRzBXZVg2Qmd2c2M" target="_blank">Download Code From Here</a><br />
<br />
Reference Links :<br />
https://developers.facebook.com/docs/guides/web/ <br />
https://developers.facebook.com/docs/reference/api/user/ <br />
<br />
<br />
<br />
<br />
<br />
<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/15420290858166123413noreply@blogger.com150