Thursday, May 1, 2014

How to Integrate Facebook in your ASP.Net website



Facebook is one of the top rated social media networking sites that impress everyone. More than 270 million users are using Facebook. 
Facebook connect -- this enables users to integrate Facebook platform to your website. This allow a user to connect with your site using the Facebook account and can share posts on your pages with friends on Facebook. The connection is established between Facebook and your website using a trusted authentication.
Before integrating Facebook on your website, you need to follow these steps:

Setting Up with Facebook

You’ll need to set up your application with Facebook. Set-up is free and happens pretty much instantaneously, because there’s no application approval process to go through.

1. Register your website with Facebook.

 

Log in to Facebook and visit the developer’s application at Facebook.com/developers. Here you can set up new applications and edit existing ones. You can also access SDK documentation and interact with the Facebook developer community.


In App Name: give the name of your site and continue. It will give you the Unique App ID/App Secret.



The URL of your website and the website URL you registered with Facebook should be same.

Note: If you want to access some additional information like Email ID etc, you have to use OAUTH (which is authorize the user and provide grant permissions to access).

2. Add Facebook DLL Refrences to your website/bin folder


  • Facebook.dll  
  • Facebook.web.dll

3. Web.config 

 

 Add the App ID/App Secret  value 
 <appSettings>
    <add key="redirect_uri" value="<your_redirect_uri>">
    <add key="AppKey" value="<your_App_ID>"/>
    <add key="AppSecret" value="<your_App_Secret>"/>
 </appSettings>

 

 4. Add Facebook login button in your login.aspx page


<asp:Panel ID="pnlLogin" runat="server">
                    <a href="https://www.facebook.com/dialog/oauth?client_id=your_app_id&redirect_uri=your_redirect_uri">
                        <img src="../../images/f_login.png"  />
                    </a>
 </asp:Panel>
<a id="lbllogout" runat="server" onserverclick="lbllogout_Click" visible="false" > </a>


For accessing some additional information like offline_access,email etc, you have to add scope feature in login like

<a href="https://www.facebook.com/dialog/oauth?client_id=your_app_id&redirect_uri=your_redirect_uri&scope=offline_access,user_status,publish_stream,email,manage_pages,user_groups">


It will ask you for allowing the permissions. Click Allow.

 5. Now add code in login.aspx.cs to access Facebook user details in your page


using Facebook.Web;
using Facebook;

string getAccessToken = "";
WebClient client = new WebClient();

 protected void Page_Load(object sender, EventArgs e)
  {
           string fbCodeGiven = Request.QueryString["code"];
            if ((fbCodeGiven != null))
            {
                WebRequest AccessTokenWebRequest = WebRequest.Create("https://graph.facebook.com
                 /oauth/access_token?client_id=" + your_App_ID + "&redirect_uri=" +
                 your_redirect_uri  +  "&client_secret=" + your_App_Secret"] + "&code=" +
                 fbCodeGiven);

                StreamReader AccessTokenWebRequestStream = new
                StreamReader(AccessTokenWebRequest.GetResponse().GetResponseStream());
                string WebRequestResponse = AccessTokenWebRequestStream.ReadToEnd();
                getAccessToken = WebRequestResponse.Substring(13, WebRequestResponse.Length -
                                                13);

                Session["getAccessToken"] = getAccessToken;
                string url, userInformation, email = null, CorrectEmail = null, id = null,
                first_name = null, last_name = null;

                Regex getValues;
                Match infoMatch;
                string username = "me";
                url = "https://graph.facebook.com/" + username + "/" + "?access_token=" +
                          getAccessToken;

                userInformation = client.DownloadString(url);
                getValues = new Regex("(?<=\"email\":\")(.+?)(?=\")");
                infoMatch = getValues.Match(userInformation);
                email = infoMatch.Value;
                CorrectEmail = email.Replace("\\u0040", "@");

                getValues = new Regex("(?<=\"id\":\")(.+?)(?=\")");
                infoMatch = getValues.Match(userInformation);
                id = infoMatch.Value;
                Session["facebookuserID"] = id;

                getValues = new Regex("(?<=\"first_name\":\")(.+?)(?=\")");
                infoMatch = getValues.Match(userInformation);
                first_name = infoMatch.Value;

                getValues = new Regex("(?<=\"last_name\":\")(.+?)(?=\")");
                infoMatch = getValues.Match(userInformation);
                last_name = infoMatch.Value;
            }
}

protected void lbllogout_Click(object sender, EventArgs e)
{
            if (Convert.ToString(Session["facebookuserID"]) != "")
            {
                string getAccessToken = Convert.ToString(Session["getAccessToken"]);
                Session.Remove("facebookuserID");
                Response.Redirect("https://www.facebook.com/logout.php?next=" + your_redirect_uri
                                                 + "&access_token=" + getAccessToken);
                Session.Remove("getAccessToken");
            }
 }

The URL supplied in the next parameter must be a URL with the same base domain as your application as defined in your app's settings.

IMPORTANT NOTE -- You must replace "your_App_ID", "your_App_Secret" with the APP ID, APP Secret you find in your application details in the Developer application on Facebook!

Download Files  loginwithfacebook.rar

6. Testing 


Now we are done with the coding. Its time for testing.

  • Run your Website 

I hope this article will give you good knowledge about integration with Facebook into your ASP.Net website. Please share your feedback and comments with us. 

No comments:

Post a Comment