Friday, 19 December 2014

Using Facebook authentication in ASP.NET MVC (Login With Facebook)

In this article I am explain Login with Facebook in MVC4.0. MVC 4 Provides an easy method to integrate social sites to your application. You can easily login to your site using facebook, twitter, google or microsoft with just a few line of code.


Here are the detailed steps on how its done

Before you can add 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 App using below Steps-

Step1-Click "Add a New App"

Step2-Choose below Option according your requirement


Step3: Write App Name

Step4: Choose Category


Step5:Put the Site Url

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


Step 7: Take note of the values for the “App ID” and “App Secret” fields as your will need these when enabling Facebook login in your ASP.NET MVC application. To view the App Secret click on the “Show” button next the the app secret.And 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”.

Next, select the Internet Application template

Now Open AuthConfig.cs file

Copy paste the appid and secret in authconfig file

Run the Application. Click On Login
Click On Facebook Button and you are login perfectly. But You are not getting Email of user it is Most impotant thing is pass scope=email while redirecting to the facebook oauth dialog. if you need additional fields which require user permission pass the same as parameters.

In the second function I am creating my own AuthenticationResult by calling functions from my custom facebook class
Facebook.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using MvcApplication1Demo.Extensions;
using MvcApplication1Demo.Include;
using System.Web.Mvc;

namespace MvcApplication1Demo.Include
{
    public class Facebook
    {


        public string Facebook_GraphAPI_Token = "https://graph.facebook.com/oauth/access_token?";
        public string Facebook_GraphAPI_Me = "https://graph.facebook.com/me?";
        public string AppID = "YOUR APP ID";
        public string AppSecret = "YOUR SECRET KEY";

       
        public IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
        {

            string token = Web.GetHTML(Facebook_GraphAPI_Token + "client_id=" + AppID + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectURI) + "%3F__provider__%3Dfacebook" + "&client_secret=" + AppSecret + "&code=" + accessCode);
            if (token == null || token == "")
            {
                return null;
            }
            string data = Web.GetHTML(Facebook_GraphAPI_Me + "fields=id,name,email,username,gender,link&access_token=" + token.Substring("access_token=", "&"));

            // this dictionary must contains
            var userData = new Dictionary<string, string>();
            userData.Add("id", data.Substring("\"id\":\"", "\""));
            userData.Add("username", data.Substring("username\":\"", "\""));
            userData.Add("name", data.Substring("name\":\"", "\""));
            userData.Add("link", data.Substring("link\":\"", "\"").Replace("\\/","/"));
            userData.Add("gender", data.Substring("gender\":\"", "\""));
            userData.Add("email", data.Substring("email\":\"", "\"").Replace("\\u0040", "@"));
            userData.Add("accesstoken", token.Substring("access_token=", "&"));
            return userData;
        }


    }
}

Class File Web . To Read HTML from URL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;

namespace MvcApplication1Demo.Include
{
    public static class Web
    {
        //
        // Get HTML
        // Author : Jitendra Gangwar
        // Date : Dec 18 2014
        // Modified : Dec 18 2014
        // Changed To Static Method
        //
        public static string GetHTML(string URL)
        {
            string connectionString = URL;

            try
            {
                System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
                myRequest.Credentials = CredentialCache.DefaultCredentials;
                //// Get the response
                WebResponse webResponse = myRequest.GetResponse();
                Stream respStream = webResponse.GetResponseStream();
                ////
                StreamReader ioStream = new StreamReader(respStream);
                string pageContent = ioStream.ReadToEnd();
                //// Close streams
                ioStream.Close();
                respStream.Close();
                return pageContent;
            }
            catch (Exception)
            {
            }
            return null;
        }
    }
}

Note:-I hope this article is helpfulfor you.Please Like and Share it....



No comments:

Post a Comment