Implement Facebook OAUTH Integration in ASP.NET Applications

You might be noticed that most of the modern applications are connecting to Social Network sites to get the user details from social website rather than re-inputting or duplicating the profile data.

In this article, I am going to show you how to authenticate to Facebook using OAUTH API, getting the access token along with its expiration and renewing the access token when it’s got expired.

Also, I will show you how to get the user data using access token with the help of FacebookC# SDK. It is not mandatory to use Facebook C# SDK, but you can also use any other Facebook SDKs available which support the access token to pull data from Facebook.

The first step is we need to create the Facebook App from the below URL:


Click on the Add a New App button as shown below which popups up create new app dialog.
Facebook Create New App

After inputting the display name (it is a name of your app), contact email and category, click on the Create App ID button.

If Facebook prompts you security check (mostly CAPTCHA), please succeed on it.

Once the Facebook App created successfully, you would be automatically navigated to Facebook App page as shown below:
Facebook APP Dashboard

In order to use the OAUTH in your applications using Facebook App, you have to configure few things in Facebook App after creating it. Here are the configuration steps which require:

Step 1: Navigate to Add Product tab in left side, and click on Get Started button which is next to Facebook Login product in right side details. And configure the OAuth settings and OAuth redirect URIs as shown below. Click on Save Changes button.
Facebook App Login Product

Step 2: By default when we create the Facebook App is under development mode. We need to bring the app to live mode from App Review tab by clicking Make <AppName> public? Checkbox as shown below:
Facebook App Make Public

Step 3: We need to copy the App ID and App Secret to out ASP.NET application to access it. You can get App ID and App Secret from Settings tab as shown below.
Facebook App ID and App Secret

You can keep the App ID and App Secret either in App Settings section of Web.Config or in database whichever you prefer. For demonstration purpose, in this article I have hardcoded the keys in program.

Now we are done with configuration part in Facebook side.

Here are the steps on how we can consume the App ID and App Secret in our ASP.NET application and performing OAUTH.

Step 1: Create a custom class called SocialAPI as given below

        public class SocialAPI
        {
            public FacebookClient FbClient;

            string appId = string.Empty;
            string appSecret = string.Empty;
            string redirectURL = string.Empty;

            public string AppId { get { return appId; } }
            public string AppSecret { get { return appSecret; } }
            public string RedirectURL { get { return redirectURL; } }

            public string AccessToken
            {
                get { return FbClient.AccessToken; }
                set { FbClient.AccessToken = value; }
            }

            public SocialAPI()
            {
                FbClient = new FacebookClient();
                appId = "<Your API ID>";
                appSecret = "<Your API Secret>";
                redirectURL = "<Your Redirect URI>";
            }
        }

Step 2: Use the below code in your Page_Load event

            SocialAPI fbAPI = new SocialAPI();
            string code = Request.QueryString["code"];

            if (string.IsNullOrEmpty(code))
            {
                Response.Redirect("https://graph.facebook.com/oauth/authorize?client_id=" + fbAPI.AppId + "&redirect_uri=" + fbAPI.RedirectURL);
            }
            else
            {               
                string[] accessTokenDetails = GetAccessTokenAndExpirationDays(code, fbAPI);

                //store access token and expiration in your database for reuse/renew it
                fbAPI.AccessToken = accessTokenDetails[0];
                string expiration = accessTokenDetails[1];

                string facebookUserName = GetUserName(fbAPI);
            }

And, here is the method to get the Facebook user’s access token and its expiration in days.

        public string[] GetAccessTokenAndExpirationDays(string code, SocialAPI fbAPI)
        {
            string uriString = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&redirect_uri={2}&code={3}", fbAPI.AppId, fbAPI.AppSecret, fbAPI.RedirectURL, code);
            Uri targetUri = new Uri(uriString);
            HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(targetUri);

            StreamReader sr = new StreamReader(httpReq.GetResponse().GetResponseStream());

            string query = sr.ReadToEnd().ToString();
            string accessToken = HttpUtility.ParseQueryString(query).Get("access_token");
            string expires = HttpUtility.ParseQueryString(query).Get("expires");

            TimeSpan ts = TimeSpan.FromSeconds(double.Parse(expires));
            expires = ts.TotalDays.ToString();

            return new string[] { accessToken, expires };
        }

I have used the Facebook C# SDK to get the Facebook user details using the access token and here is the sample code I have used to get username.

        public string GetUserName(SocialAPI fbAPI)
        {
            try
            {
                dynamic userProfile = fbAPI.FbClient.Get("me?fields=id,name,birthday,email,education,photos{picture,album},cover");
                return userProfile.name;
            }
            catch (FacebookApiException ex)
            {
                return ex.Message;
            }
        }

That’s it. When you run the above code, the end user is forcefully directed to Facebook OAUTH login page as shown below. Once he successfully authenticated to our newly created Facebook App, he will be redirected back to our application to the given redirect URI where we are getting user’s access token and its expiration.
Facebook OAUTH Login
Step 3: In case if the Facebook user access token was expired or going to expire, use the below code to renew it.

        public string[] GetRenewedAccessTokenAndExpirationDays(string oldAccessToken, SocialAPI fbAPI)
        {    
            //get security code
            Uri targetUri = new Uri("https://graph.facebook.com/oauth/client_code?access_token=" + oldAccessToken + "&client_secret=" + fbAPI.AppSecret + "&redirect_uri=" + fbAPI.RedirectURL + "&client_id=" + fbAPI.AppId);
            HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(targetUri);

            StreamReader str = new StreamReader(httpReq.GetResponse().GetResponseStream());

            string query = str.ReadToEnd().ToString();           

            var data = (JObject)JsonConvert.DeserializeObject(query);
            string code = data["code"].Value<string>();

            //get new access token
            targetUri = new Uri("https://graph.facebook.com/oauth/access_token?client_id=" + fbAPI.AppId + "&client_secret=" + fbAPI.AppSecret + "&redirect_uri=" + fbAPI.RedirectURL + "&code=" + code);
            httpReq = (HttpWebRequest)HttpWebRequest.Create(targetUri);

            str = new StreamReader(httpReq.GetResponse().GetResponseStream());

            query = str.ReadToEnd().ToString();
            data = (JObject)JsonConvert.DeserializeObject(query);
            string accessToken = data["access_token"].Value<string>();
            string expires = data["expires_in"].Value<string>();

            TimeSpan ts = TimeSpan.FromSeconds(double.Parse(expires));
            expires = ts.TotalDays.ToString();

            return new string[] { accessToken, expires };
        }

Facebook References:

Done! Now you got to know how to do Facebook OAuth login in ASP.NET. If you have any question please throw a comment in below comment box.

Thanks for reading…..

1 comment:

  1. Simply wish to say your article is as astounding. The clearness
    for your publish is simply spectacular and
    that i can assume you're knowledgeable on this subject.

    Well together with your permission let me to snatch your feed to stay
    updated with imminent post. Thank you a million andd please continue the enjoyable work.

    ReplyDelete

Powered by Blogger.