Using Facebook Authentication in ASP.Net MVC

You can easily login to your site using Facebook, Twitter, Google or Microsoft with just a few lines of code.

Procedure on how it is done

Before you can add a Facebook login to your web application you will need to register a new Facebook application. Head over to the Facebook Developer page and select “Create a New App” from the Apps menu at the top of the page.

Create App

Create an app using the following procedure.

Step 1

Click "Add a New App".

graph api

Step 2

Choose the following option depending on your requirements.

add new app

Step 3

Provide App Name.

quick start for website

Step 4

Choose Category.

create new app id

Step 5

Provide the Site URL.

sdk setup

Step 6

Click on the “Settings” menu in the left hand navigation bar.

setting

Step 7

Take note of the values for the “App ID” and “App Secret” fields since you will need these when enabling the Facebook login in your ASP.NET MVC application. To view the App Secret click on the “Show” button next to the app secret and add your Contact Email.

Add Your Contact Email

Now Enabling Facebook authentication in your ASP.NET MVC Application

The next step is to add the Facebook login to your ASP.NET MVC application. For this we will create a new ASP.NET MVC application using Visual Studio. Go to "File" -> "New" -> "Project..." and select the template for a new “ASP.NET Web Application” and click “OK”.

web application

Next, select the Internet Application template.

internet application

Now open the AuthConfig.cs file.

soluction explorer

Copy and paste the appid and secret into the authconfig file.

home page

login

Run the application. Click on Login.

Click on the Facebook Button and you are logged in perfectly. But you are not getting the Email of the user. That is the most important thing so scope=email while redirecting to Facebook of the dialog. If you need additional fields that require user permission then them as parameters.

In the second function I am creating my own AuthenticationResult by calling functions from my custom Facebook class.

Facebook.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. using MvcApplication1Demo.Extensions;  
  7. using MvcApplication1Demo.Include;  
  8. using System.Web.Mvc;  
  9.   
  10. namespace MvcApplication1Demo.Include  
  11. {  
  12.     public class Facebook  
  13.     {
  14.         public string Facebook_GraphAPI_Token = "https://graph.facebook.com/oauth/access_token?";  
  15.         public string Facebook_GraphAPI_Me = "https://graph.facebook.com/me?";  
  16.         public string AppID = "YOUR APP ID";  
  17.         public string AppSecret = "YOUR SECRET KEY";
  18.         public IDictionary<stringstring> GetUserData(string accessCode, string redirectURI)  
  19.         {  
  20.   
  21.             string token = Web.GetHTML(Facebook_GraphAPI_Token + "client_id=" + AppID + "&redirect_uri="+ HttpUtility.HtmlEncode(redirectURI) + "%3F__provider__%3Dfacebook" + "&client_secret=" + AppSecret +"&code=" + accessCode);  
  22.             if (token == null || token == "")  
  23.             {  
  24.                 return null;  
  25.             }  
  26.             string data = Web.GetHTML(Facebook_GraphAPI_Me +"fields=id,name,email,username,gender,link&access_token=" + token.Substring("access_token=""&"));  
  27.   
  28.             // this dictionary must contains  
  29.             var userData = new Dictionary<stringstring>();  
  30.             userData.Add("id", data.Substring("\"id\":\"""\""));  
  31.             userData.Add("username", data.Substring("username\":\"""\""));  
  32.             userData.Add("name", data.Substring("name\":\"""\""));  
  33.             userData.Add("link", data.Substring("link\":\"""\"").Replace("\\/","/"));  
  34.             userData.Add("gender", data.Substring("gender\":\"""\""));  
  35.             userData.Add("email", data.Substring("email\":\"""\"").Replace("\\u0040""@"));  
  36.             userData.Add("accesstoken", token.Substring("access_token=""&"));  
  37.             return userData;  
  38.         }
  39.     }  
  40. }  
Class file web to read HTML from URL:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Net;  
  6. using System.IO;  
  7.   
  8. namespace MvcApplication1Demo.Include  
  9. {  
  10.     public static class Web  
  11.     {  
  12.         //  
  13.         // Get HTML  
  14.         // Author : Jitendra Gangwar  
  15.         // Date : Dec 18 2014  
  16.         // Modified : Dec 18 2014  
  17.         // Changed To Static Method  
  18.         //  
  19.         public static string GetHTML(string URL)  
  20.         {  
  21.             string connectionString = URL;  
  22.   
  23.             try  
  24.             {  
  25.                 System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);  
  26.                 myRequest.Credentials = CredentialCache.DefaultCredentials;  
  27.                 //// Get the response  
  28.                 WebResponse webResponse = myRequest.GetResponse();  
  29.                 Stream respStream = webResponse.GetResponseStream();  
  30.                 ////  
  31.                 StreamReader ioStream = new StreamReader(respStream);  
  32.                 string pageContent = ioStream.ReadToEnd();  
  33.                 //// Close streams  
  34.                 ioStream.Close();  
  35.                 respStream.Close();  
  36.                 return pageContent;  
  37.             }  
  38.             catch (Exception)  
  39.             {  
  40.             }  
  41.             return null;  
  42.         }  
  43.     }  
  44. }  
Note: I hope this article is helpful for you. Please Like and Share it.


Similar Articles