Click here to Skip to main content
15,881,882 members
Articles / Web Development / HTML

Using Facebook Login in ASP.NET Application Without Any Third Party Library

Rate me:
Please Sign up or sign in to vote.
4.75/5 (18 votes)
31 Aug 2012CPOL3 min read 262.8K   43   48
How to use Facebook login in ASP.NET application without any third party library

Facebook is extremely popular these days and you will hardly find anyone without a Facebook profile. More and more people now want their 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 a step by step demo on how to integrate Facebook login into you screen.

Step 1: Register Site in Facebook

In order to use Facebook login, you should have a verified developer account in Facebook (which is very easy to create. Just login to http://developers.facebook.com using your Facebook credentials and follow the screen instructions) and you must register your website in the form of an App in Facebook.

So let's start with registering your site with Facebook:

  1. Open http://developers.facebook.com and login with your Facebook credentials. After logging in, you will get a screen like this:

    Image 1

  2. Click on "Build for Websites" link, you will reach https://developers.facebook.com/docs/guides/web/, just click on 'Apps' menu Items (the last menu Item from right side), you will reach https://developers.facebook.com/apps. Click on Image 2 button, you will get the following screen:

    Image 3

  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 the below screenshot (Just masked the AppID).

    Image 4

  4. Give the URL of your website/ application Site URL text box of the app summary screen, like the 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.

    Image 5

Now you are ready to create an ASP.NET Web Application, to use Facebook integration.

Step 2: Create ASP.NET Application using Facebook Login

  1. Open Visual Studio.
  2. Select File --> New --> Project/Solution --> 'ASP.NET Empty Application'
  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.)

    Image 6

  4. We will be doing most of the code on the HTML code of ASP.NET Page.
  5. For using Facebook login, we will have to use Facebook JavaScript SDK. There are three ways of using it:
    1. Load the JavaScript SDK asynchronously:
       <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>
      
    2. Load the JavaScript SDK synchronously:
      <script src=https://connect.facebook.net/en_US/all.js type="text/javascript"></script>
    3. Download the SDK JavaScript file in your local project folder and use it from there. Implemented in 'Default.aspx' of solution.
      <script src="scripts/all.js" type="text/javascript"></script>
  6. We will also require jquery for initializing the library, so copy the following code in the header section of the page.
    JavaScript
    <script
    src="scripts/jquery-1.8.0.min.js"
    type="text/javascript"></script> <script
    src="scripts/all.js"
    type="text/javascript"></script> 7) Now to initialize the Facebook SDK 
    copy following code in a new script section :
             $("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);
            });

    Here, YOUR_APP_ID will be the App Id you will get from the Facebook App.

  7. Also, copy the following code after the above code to get the response back and fill the values.
    // 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';
                        }
    }
    
  8. Copy the following code in the Body tag of the Page.
    <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>
    
  9. Your application is ready now, execute the application.

In this blog, we have learned how to register an application in Facebook and then 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.

Reference Links

License

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


Written By
Architect
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 : http://techierathore.com/

Comments and Discussions

 
Suggestionadditional help Pin
roger_276-Jan-13 6:24
roger_276-Jan-13 6:24 
This article was very good. and current. The big problem is stupid facebook keeps changing their interface so this tutorial (unless constantly updated every other month) is eventually going to have different screenshots than the real site Frown | :(

Anyways I just wanted to add some advice to people who (like me) wanted to populate ASP.NET SERVER SIDE controls, and not just fill a few <span> tags:

in the LoadValues Function, change it to look like this...


<pre lang="Javascript">
//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';

//the difference begins here. I added 3 ASP.NEt controls.
//I also commented out the clicking of a button
//THE CONTROLS CAN ONLY BE A TEXTBOX OR an <asp:Hidden> FIELD!!!!!!!
//NO LABELS OR ANYTHING ELSE!!!!!
//you can set the textbox style="display:none" or width="0"
document.getElementById("txtFbName").value = me.name;
document.getElementById("txtFbID").value = me.id;
document.getElementById("txtFbEmail").value = me.email;

//If you want it to automatically click an ASP.NET button
//on login, you use this (obviously you uncomment it though).
// document.getElementById("btnDummy").click();
//difference ends here
}
}
</pre>



then on the same page but inside your ASP.NET <form> tags, make your ASP.NET controls but make sure their CLIENT ID IS STATIC. this prevents asp.net from changing the name of the control to
ctl_00txtFbName
or whatever. Just be careful because this means if you have ANY OTHER elements that ARENT asp.net, you need to make sure they don't have the same name.

<pre lang="HTML">
You are currently logged in as: <asp:TextBox ID="txtFbName" runat="server" ClientIDMode="Static"></asp:TextBox> <br />
Your FacebookID is: <asp:TextBox ID="txtFbID" runat="server" ClientIDMode="Static"></asp:TextBox> <br />
Your email is: <asp:TextBox ID="txtFbEmail" runat="server" ClientIDMode="Static"></asp:TextBox> <br />
</pre>

now if you want a button to get clicked on login, you need to add the button to the ASPX page BUT put it in an update panel:

<pre lang="HTML">
<asp:UpdatePanel ID="updaterix" runat="server">
<ContentTemplate>
<asp:Button ID="btnAddReplyInFB" runat="server"
ClientIDMode="Static" onclick="btnTestGo_Click"
Text="Add Reply in FB" style="display: none;" />
</ContentTemplate>
</asp:UpdatePanel>
</pre>

notice the style="display:none;" on the button. this is going to be an INVISIBLE button that gets clicked on FB login. You can add whatever button click code to this in the C# / VB net code click event.


lastly, I was noticing that the code was executing on both LOGIN and LOGOUT, so I changed this method:

<pre lang="Javascript">
// 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);
}
}
</pre>

To This Method:
<pre lang="Javascript">
//I changed the method name so I don't actually
//replace the method in case I need to
//revert back. you can do whaterver you want
function getLoginStatus(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
// var uid = response.authResponse.userID;
// var accessToken = response.authResponse.accessToken;

//show whatever controls you need to show
//now that the user has successfully logged in!
document.getElementById("btnAddReplyInFB").style.display = 'block';
document.getElementById("pnlReplyPanel").style.display = 'block';
FB.api('/me?fields=id,name,gender,email,birthday', LoadValues);
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app

//hide reply button for facebok users
document.getElementById("btnAddReplyInFB").style.display = 'none';
document.getElementById("pnlReplyPanel").style.display = 'none';


} else {
// the user isn't logged in to Facebook.
//hide reply button for facebok users
document.getElementById("btnAddReplyInFB").style.display = 'none';
document.getElementById("pnlReplyPanel").style.display = 'none';


}
};

</pre>




obviously if you change the method so you dont delete the old method, you need to change
//old method
FB.Event.subscribe('auth.statusChange', OnLogin);
to
//new mthod
FB.Event.subscribe('auth.statusChange', getLoginStatus);



This is still a work in progress for me, but all of that should work so far I Think. I havent actually tested that last "else" condition in the code block above yet. but everything else is working fine for me.

I hope this helps someone because it took me a while to figure out.
one final thought YOU CANT TEST THIS ON LOCALHOST! I know this is answered like 10 times in the other commentso n this page but it keeps coming up. YOU CAN ONLY GET FB USER INFO WHEN YOU TEST IT ON A LIVE SERVER!

Thanks.

Hopefully you'll be able to see this in my site live in my site
http://www.WhoPostsThisStuff.com
some time after january 2013

It's not a bug it's a f- oh wait... no..It's a bug.
GeneralRe: additional help Pin
Gianluca SamBuca Di Pietro5-Feb-13 8:56
Gianluca SamBuca Di Pietro5-Feb-13 8:56 
GeneralRe: additional help Pin
roger_276-Feb-13 3:28
roger_276-Feb-13 3:28 
GeneralRe: additional help Pin
Gianluca SamBuca Di Pietro8-Feb-13 0:03
Gianluca SamBuca Di Pietro8-Feb-13 0:03 
GeneralRe: additional help Pin
roger_2710-Feb-13 11:58
roger_2710-Feb-13 11:58 
GeneralRe: additional help Pin
Tom Psillas21-Oct-14 16:55
Tom Psillas21-Oct-14 16:55 
GeneralMy vote of 5 Pin
Rafael Nicoletti20-Dec-12 6:18
Rafael Nicoletti20-Dec-12 6:18 
Questionlogin with facebook problem Pin
hasanbudak24-Nov-12 6:57
hasanbudak24-Nov-12 6:57 
AnswerRe: login with facebook problem Pin
S Ravi Kumar (TechieRathore)3-Jan-13 19:55
professionalS Ravi Kumar (TechieRathore)3-Jan-13 19:55 
QuestionFb.Event.Subscribe Pin
safiyullah4-Sep-12 20:48
safiyullah4-Sep-12 20:48 
AnswerRe: Fb.Event.Subscribe Pin
S Ravi Kumar (TechieRathore)5-Sep-12 2:29
professionalS Ravi Kumar (TechieRathore)5-Sep-12 2:29 
GeneralRe: Fb.Event.Subscribe Pin
safiyullah5-Sep-12 18:39
safiyullah5-Sep-12 18:39 
GeneralRe: Fb.Event.Subscribe Pin
S Ravi Kumar (TechieRathore)6-Sep-12 15:43
professionalS Ravi Kumar (TechieRathore)6-Sep-12 15:43 
GeneralRe: Fb.Event.Subscribe Pin
safiyullah6-Sep-12 18:46
safiyullah6-Sep-12 18:46 
GeneralRe: Fb.Event.Subscribe Pin
safiyullah17-Sep-12 18:41
safiyullah17-Sep-12 18:41 
GeneralRe: Fb.Event.Subscribe Pin
S Ravi Kumar (TechieRathore)19-Sep-12 19:08
professionalS Ravi Kumar (TechieRathore)19-Sep-12 19:08 
GeneralRe: Fb.Event.Subscribe Pin
safiyullah20-Sep-12 3:44
safiyullah20-Sep-12 3:44 
GeneralRe: Fb.Event.Subscribe Pin
S Ravi Kumar (TechieRathore)14-Nov-12 23:20
professionalS Ravi Kumar (TechieRathore)14-Nov-12 23:20 
AnswerRe: Fb.Event.Subscribe Pin
Danko Greiner23-Jan-13 22:33
Danko Greiner23-Jan-13 22:33 
GeneralRe: Fb.Event.Subscribe Pin
S Ravi Kumar (TechieRathore)10-Mar-13 8:20
professionalS Ravi Kumar (TechieRathore)10-Mar-13 8:20 
QuestionMy vote of 3 (almost 4) Pin
Rafael Nicoletti2-Sep-12 15:28
Rafael Nicoletti2-Sep-12 15:28 
AnswerRe: My vote of 3 (almost 4) Pin
S Ravi Kumar (TechieRathore)2-Sep-12 18:20
professionalS Ravi Kumar (TechieRathore)2-Sep-12 18:20 
GeneralMy vote of 4 Pin
Prabhakaran Soundarapandian31-Aug-12 6:53
Prabhakaran Soundarapandian31-Aug-12 6:53 

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.