Click here to Skip to main content
12,398,000 members (52,671 online)
Click here to Skip to main content
Add your own
alternative version


14 bookmarked

Implement Facebook Login with OpenID Selector in MVC3

, 3 Sep 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
In My last post, I explained how we can implement Facebook login with OpenId selector tool.
In My last post, 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.

1- Open Visual Studio 2010 go to File > New > Project > Web > ASP.NET MVC 3 Application:

then Choose Internet Application be sure to have Razor as your View engine and Click OK:
2- Download DotNetOpenAuth dll and Updated OpenID Selector files that we will use.
      A- Add the DotNetOpenAuth.dll to references in your site.
      B- Copy all contents of openid-selector\css folder to the 'Content' folder .
      C- Copy images, images.large, images.small folders to the site 'Content' folder.
      D- Copy openid-jquery.js, openid-en.js files from  openid-selector\js folder to 'Scripts' folder

Your Solution Explorer  will look like this (See Highlighted Portion)  :

 3- Go to Views > Shared > _Layout.cshtml and replace the <head> with this new head with new styles and scripts:
    <meta charset="utf-8" />
    <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=""> </script>
    <script type="text/javascript">
        $(document).ready(function () {

<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>
<span class="kwrd">   <span style="color: black;">and Add <span style="color: blue;">OpenID</span>
<span class="kwrd"><span style="color: black;">  your class will look like this:</span></span>
public class LogOnModel
    [Display(Name = "OpenID")]
    public string OpenID { get; set; }

    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }

<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>
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; }
<span class="kwrd"><span style="color: black;"> </span></span><span class="kwrd"><span style="color: black;"> </span></span>
<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>
<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>
<span class="kwrd"><span style="color: black;"> </span></span>
<span class="kwrd"><span style="color: black;"> </span></span>
@model FBOpenIDMVC3.Models.LogOnModel

    ViewBag.Title = "Log On";    
    Log On</h2>
    Please enter your username and password. @Html.ActionLink("Register", "Register")
    if you don't have an account.
<script type="text/javascript">
    $(document).ready(function () {
        // Init the SDK upon load
        window.fbAsyncInit = function () {
                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() {
    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 ( {
                    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_',;
                    url = url.replace('_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_',;
                    window.location.href = url;
7- Update the value of img_path in openid-jquery.js to '../Content/images/'
8- Now let us run the project , then click the [Log On] link , you will get like this page:
<span class="kwrd"><span style="color: black;">9- Now to implement Open ID using DotnetOpenAuth, Go to Controllers > </span></span>
<span class="kwrd"><span style="color: black;">AccountController.cs and Add these using:</span></span>
<span class="kwrd"><span style="color: black;"> </span></span>
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
Then Add the following code to AccountController.cs:
private static OpenIdRelyingParty openid = new OpenIdRelyingParty();

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))
                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));
                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;
                        case WellKnownAttributes.Contact.Email:
                            var emailAddresses = fetch.Attributes[WellKnownAttributes.Contact.Email].Values;
                            sEmail = emailAddresses.Count > 0 ? emailAddresses[0] : null;
                        case WellKnownAttributes.Name.Last:
                            var lastNames = fetch.Attributes[WellKnownAttributes.Name.Last].Values;
                            sLastName = lastNames.Count > 0 ? lastNames[0] : null;
                        case WellKnownAttributes.Person.Gender:
                            var genders = fetch.Attributes[WellKnownAttributes.Person.Gender].Values;
                            sGender = genders.Count > 0 ? genders[0] : null;
                        case WellKnownAttributes.BirthDate.WholeBirthDate:
                            var doBs = fetch.Attributes[WellKnownAttributes.BirthDate.WholeBirthDate].Values;
                            sDob = doBs.Count > 0 ? doBs[0] : null;
            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);
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);
10 - Right Click on Views--> Accounts and Click Add-->View to add new view like this:
11- Add following code in this View:
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; }
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 :
Congratulations  ,  now you had integrated OpenID login with facebook login to your project.

Download Code from here


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

S Ravi-Kumar-2012
India India
Hi There, I am an IT professional with 14 years of experience in architecting, designing and building IT solutions for complex business needs in form of mobile & web applications using Microsoft technologies. Currently working in an multinational company in India as Solutions Architect. The articles here are sourced from my blog :

You may also be interested in...

Comments and Discussions

QuestionFacebook butoon unclikable Pin
Shashi Kant Yadav25-Oct-13 1:44
memberShashi Kant Yadav25-Oct-13 1:44 
AnswerRe: Facebook butoon unclikable Pin
S Ravi Kumar-201210-Nov-13 20:35
memberS Ravi Kumar-201210-Nov-13 20:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 3 Sep 2012
Article Copyright 2012 by S Ravi-Kumar-2012
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid