Click here to Skip to main content
13,251,760 members (66,237 online)
Click here to Skip to main content
Add your own
alternative version

Stats

178.2K views
41 bookmarked
Posted 31 Aug 2012

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

, 31 Aug 2012
Rate this:
Please Sign up or sign in to vote.
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:

  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 button, you will get the following screen:

  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).

  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.

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.)

  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.
    <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)

Share

About the Author

S Ravi-Kumar-2012
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://err2solution.com/

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionscreen shot images Pin
Member 1205052211-Oct-15 11:17
memberMember 1205052211-Oct-15 11:17 
QuestionNot working Pin
bobbybunty9-May-14 5:31
memberbobbybunty9-May-14 5:31 
QuestionObject doesn't support property or method '_gcb2' Pin
bishu_Visu7-Jan-14 1:48
memberbishu_Visu7-Jan-14 1:48 
AnswerRe: Object doesn't support property or method '_gcb2' Pin
S Ravi Kumar-20127-Jan-14 7:02
memberS Ravi Kumar-20127-Jan-14 7:02 
GeneralRe: Object doesn't support property or method '_gcb2' Pin
bishu_Visu7-Jan-14 22:52
memberbishu_Visu7-Jan-14 22:52 
GeneralRe: Object doesn't support property or method '_gcb2' Pin
bishu_Visu8-Jan-14 21:14
memberbishu_Visu8-Jan-14 21:14 
Questionthanks Pin
Member 97211334-Jan-14 1:24
memberMember 97211334-Jan-14 1:24 
QuestionHow can i solve this error Pin
KM Perumal10-Nov-13 20:40
groupKM Perumal10-Nov-13 20:40 
AnswerRe: How can i solve this error Pin
S Ravi Kumar-201210-Nov-13 21:34
memberS Ravi Kumar-201210-Nov-13 21:34 
QuestionUser information doesn't display Pin
Member 810335113-Jul-13 6:02
memberMember 810335113-Jul-13 6:02 
QuestionPage_Load retrieve user id Pin
Member 921312624-Jun-13 7:41
memberMember 921312624-Jun-13 7:41 
QuestionRedirect to other page after Login Pin
Venkatesh Yeluri11-Jun-13 16:52
memberVenkatesh Yeluri11-Jun-13 16:52 
QuestionMy vote of 5 Pin
KevinJeremy15-May-13 2:41
memberKevinJeremy15-May-13 2:41 
Questionget city and country Pin
shanalikhan10-Mar-13 12:43
membershanalikhan10-Mar-13 12:43 
AnswerRe: get city and country Pin
S Ravi Kumar-201211-Mar-13 3:06
memberS Ravi Kumar-201211-Mar-13 3:06 
Questionunable to see information Pin
shanalikhan10-Mar-13 3:04
membershanalikhan10-Mar-13 3:04 
AnswerRe: unable to see information Pin
S Ravi Kumar-201210-Mar-13 7:17
memberS Ravi Kumar-201210-Mar-13 7:17 
GeneralRe: unable to see information Pin
shanalikhan10-Mar-13 9:26
membershanalikhan10-Mar-13 9:26 
GeneralRe: unable to see information Pin
S Ravi Kumar-201210-Mar-13 9:31
memberS Ravi Kumar-201210-Mar-13 9:31 
GeneralRe: unable to see information Pin
shanalikhan10-Mar-13 9:40
membershanalikhan10-Mar-13 9:40 
QuestionAwful tutorial and misleading title Pin
d-signet228-Feb-13 10:35
memberd-signet228-Feb-13 10:35 
GeneralRe: Awful tutorial and misleading title Pin
mafnx14-Mar-13 6:24
membermafnx14-Mar-13 6:24 
QuestionCan I do the same concept for my Windows Application? Pin
Ganeshcse13-Feb-13 8:03
memberGaneshcse13-Feb-13 8:03 
QuestionIs there any security threat for my application Pin
SumanBiswas24-Jan-13 11:23
memberSumanBiswas24-Jan-13 11:23 
AnswerRe: Is there any security threat for my application Pin
S Ravi Kumar-201211-Jan-15 19:45
memberS Ravi Kumar-201211-Jan-15 19:45 
Suggestionadditional help Pin
roger_276-Jan-13 7:24
memberroger_276-Jan-13 7:24 
GeneralRe: additional help Pin
Gianluca SamBuca Di Pietro5-Feb-13 9:56
memberGianluca SamBuca Di Pietro5-Feb-13 9:56 
GeneralRe: additional help Pin
roger_276-Feb-13 4:28
memberroger_276-Feb-13 4:28 
GeneralRe: additional help Pin
Gianluca SamBuca Di Pietro8-Feb-13 1:03
memberGianluca SamBuca Di Pietro8-Feb-13 1:03 
GeneralRe: additional help Pin
roger_2710-Feb-13 12:58
memberroger_2710-Feb-13 12:58 
GeneralRe: additional help Pin
Tom Psillas21-Oct-14 17:55
memberTom Psillas21-Oct-14 17:55 
GeneralMy vote of 5 Pin
Rafael Nicoletti20-Dec-12 7:18
memberRafael Nicoletti20-Dec-12 7:18 
Questionlogin with facebook problem Pin
hasanbudak24-Nov-12 7:57
memberhasanbudak24-Nov-12 7:57 
AnswerRe: login with facebook problem Pin
S Ravi Kumar-20123-Jan-13 20:55
memberS Ravi Kumar-20123-Jan-13 20:55 
QuestionFb.Event.Subscribe Pin
safiyullah4-Sep-12 21:48
membersafiyullah4-Sep-12 21:48 
AnswerRe: Fb.Event.Subscribe Pin
S Ravi Kumar-20125-Sep-12 3:29
memberS Ravi Kumar-20125-Sep-12 3:29 
GeneralRe: Fb.Event.Subscribe Pin
safiyullah5-Sep-12 19:39
membersafiyullah5-Sep-12 19:39 
GeneralRe: Fb.Event.Subscribe Pin
S Ravi Kumar-20126-Sep-12 16:43
memberS Ravi Kumar-20126-Sep-12 16:43 
GeneralRe: Fb.Event.Subscribe Pin
safiyullah6-Sep-12 19:46
membersafiyullah6-Sep-12 19:46 
GeneralRe: Fb.Event.Subscribe Pin
safiyullah17-Sep-12 19:41
membersafiyullah17-Sep-12 19:41 
Hi RaviKumar,

As you mentioned your article FB Login button and FB Like button works perfectly in firefox and chrome. But IE8 having problem in login authentication popup. When we click login button in IE8 the authentication popup window openend, after we click login in popup window its throw the below error.
Please let me know if you have any solution.


Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
Timestamp: Tue, 18 Sep 2012 04:37:47 UTC


Message: 'closed' is null or not an object
Line: 1
Char: 784
Code: 0
URI: https://www.facebook.com/plugins/close_popup.php?reload=https%3A%2F%2Fwww.facebook.com%2Fplugins%2Flogin_button.php%3Fapi_key%3D182435891891124%26auto_logout_link%3Dtrue%26channel%3Dhttp%253A%252F%252Fstatic.ak.facebook.com%252Fconnect%252Fxd_arbiter.php%253Fversion%253D11%2523cb%253Df3dfc14eb8962b8%2526origin%253Dhttp%25253A%25252F%25252Flocalhost%25252Ff2d56a5c19f6774%2526domain%253Dlocalhost%2526relation%253Dparent.parent%26locale%3Den_US%26login_text%3DLogin%2Bwith%2BFacebook%2B%26scope%3Duser_birthday%252Cemail%26sdk%3Djoey%26ret%3Dperms%26hash%3DAQDonIMY4vUvZS0f&perms=user_birthday%2Cemail&selected_profiles=100001481973936

Thanks & Regards
Safiyullah
GeneralRe: Fb.Event.Subscribe Pin
S Ravi Kumar-201219-Sep-12 20:08
memberS Ravi Kumar-201219-Sep-12 20:08 
GeneralRe: Fb.Event.Subscribe Pin
safiyullah20-Sep-12 4:44
membersafiyullah20-Sep-12 4:44 
GeneralRe: Fb.Event.Subscribe Pin
S Ravi Kumar-201215-Nov-12 0:20
memberS Ravi Kumar-201215-Nov-12 0:20 
AnswerRe: Fb.Event.Subscribe Pin
Danko Greiner23-Jan-13 23:33
memberDanko Greiner23-Jan-13 23:33 
GeneralRe: Fb.Event.Subscribe Pin
S Ravi Kumar-201210-Mar-13 9:20
memberS Ravi Kumar-201210-Mar-13 9:20 
QuestionMy vote of 3 (almost 4) Pin
Rafael Nicoletti2-Sep-12 16:28
memberRafael Nicoletti2-Sep-12 16:28 
AnswerRe: My vote of 3 (almost 4) Pin
S Ravi Kumar-20122-Sep-12 19:20
memberS Ravi Kumar-20122-Sep-12 19:20 
GeneralMy vote of 4 Pin
Prabhakaran Soundarapandian31-Aug-12 7:53
memberPrabhakaran Soundarapandian31-Aug-12 7: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 31 Aug 2012
Article Copyright 2012 by S Ravi-Kumar-2012
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid