Facebook Integration By Using oAuth

There are many ways to integrate the Facebook by Oauth like "RegisterFacebookClient". But I have some issues with this method, as I get isSuccussfull=false all the time. With this, I have to integrate Facbook easily. I hope this will help others too.
 
Firstly, create a New ASp.Net MVC 4 Web Application project in Visual Studio 2012 and select "Internet Application".
 
 
Before creating a .NET MVC application, we have to register the domain name that will be used for the web site at the Facebook development site: https://developers.facebook.com/apps. After this, we will have an "App ID" and "App Secret".

Create New App

1. Click on the Add a New App.

 
2. Then Enter the Display name like "Demo" and Contact Email. After this click on "Create App ID".

 
Then your app is created. Now you have to set the basic settings of the App. Then select "Platform" and click on "Web". Now you have to enter your "Site URL". 


Then go to the App Review menu and make your app live. After making your app live, a popup will be displayed on the screen in which you have to select the category of your app like "Pages" to make your app public. So, it will become available to everyone.



Now your app is ready to integrate.
 
I have registered my class named as "FacebookScopedClient.cs" for Facebook. Write a one line code in AuthConfig.cs
  1. OAuthWebSecurity.RegisterClient(new FacebookScopedClient("YourAppId""YourSecretId"), "Facebook", null);  
Here is the code for FacebookScopedClient.cs class which has inherited IAuthenticationClient Interface.
  1. public class FacebookScopedClient : IAuthenticationClient  
  2.     {  
  3.         private string appId;  
  4.         private string appSecret;  
  5.           
  6.         private const string baseUrl = "https://www.facebook.com/dialog/oauth?client_id=";  
  7.         public const string graphApiToken = "https://graph.facebook.com/oauth/access_token?";  
  8.         public const string graphApiMe = "https://graph.facebook.com/me?";  
  9.   
  10.   
  11.         private static string GetHTML(string URL)  
  12.         {  
  13.             string connectionString = URL;  
  14.   
  15.             try  
  16.             {  
  17.                 System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);  
  18.                 myRequest.Credentials = CredentialCache.DefaultCredentials;  
  19.                 //// Get the response  
  20.                 WebResponse webResponse = myRequest.GetResponse();  
  21.                 Stream respStream = webResponse.GetResponseStream();  
  22.                 ////  
  23.                 StreamReader ioStream = new StreamReader(respStream);  
  24.                 string pageContent = ioStream.ReadToEnd();  
  25.                 //// Close streams  
  26.                 ioStream.Close();  
  27.                 respStream.Close();  
  28.                 return pageContent;  
  29.             }  
  30.            catch (WebException ex)  
  31.             {  
  32.                 StreamReader reader = new StreamReader(ex.Response.GetResponseStream());  
  33.                 string line;  
  34.                 StringBuilder result = new StringBuilder();  
  35.                 while ((line = reader.ReadLine()) != null)  
  36.                 {  
  37.                     result.Append(line);  
  38.                 }  
  39.   
  40.             }  
  41.             catch (Exception)  
  42.             {  
  43.             }  
  44.             return null;  
  45.         }  
  46.   
  47.           
  48.         private IDictionary<string, string> GetUserData(string accessCode, string redirectURI)  
  49.         {  
  50.             string value = "";  
  51.             string token = GetHTML(graphApiToken + "client_id=" + appId + "&redirect_uri=" + 
  52.                                     HttpUtility.UrlEncode(redirectURI) + "&client_secret=" + 
  53.                                        appSecret + "&code=" + accessCode);  
  54.             if (token == null || token == "")  
  55.             {  
  56.                 return null;  
  57.             }  
  58.             if (token != null || token != "")  
  59.             {  
  60.                 if (token.IndexOf("access_token") > -1)  
  61.                 {  
  62.                     string[] arrtoken = token.Replace("\''""").Split(':');  
  63.                     string[] arrval = arrtoken[1].ToString().Split(',');  
  64.                     value = arrval[0].ToString().Replace("\"""");  
  65.                 }  
  66.             }  
  67.             string data = GetHTML(graphApiMe + "fields=id,name,email,gender,link&access_token=" + value);  
  68.               
  69.   
  70.             // this dictionary must contains  
  71.         Dictionary<string, string> userData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);  
  72.          return userData;  
  73.         }  
  74.           
  75.   
  76.         public FacebookScopedClient(string appId, string appSecret)  
  77.         {  
  78.             this.appId = appId;  
  79.             this.appSecret = appSecret;  
  80.         }  
  81.   
  82.         public string ProviderName  
  83.         {  
  84.             get { return "Facebook"; }  
  85.         }  
  86.   
  87.         public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl)  
  88.         {  
  89.             string url = baseUrl + appId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) 
  90.                         + "&scope=email";  
  91.             context.Response.Redirect(url);  
  92.         }  
  93.   
  94.         public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)  
  95.         {  
  96.             string code = context.Request.QueryString["code"];  
  97.   
  98.             string rawUrl = context.Request.Url.OriginalString;  
  99.             //From this we need to remove code portion  
  100.             rawUrl = Regex.Replace(rawUrl, "&code=[^&]*""");  
  101.   
  102.             IDictionary<string, string> userData = GetUserData(code, rawUrl);  
  103.   
  104.             if (userData == null)  
  105.                 return new AuthenticationResult(false, ProviderName, null, null, null);  
  106.   
  107.             string id = userData["id"];  
  108.             string username = userData["email"];  
  109.             userData.Remove("id");  
  110.             userData.Remove("email");  
  111.   
  112.             AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData);  
  113.             return result;  
  114.         }  
  115.     }    
In your Account controller, under ExternalLoginCallback method you will find that the result will give IsSuccessful=true.
  1. AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback"
  2.                                                                      new { ReturnUrl = returnUrl }));  
Note

There will be no change in the AccountController.