Monday, 11 June 2012

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.

17 comments:

  1. I cannot Download file Above,,,, I want it
    http://techterabyte.blogspot.in/

    ReplyDelete
  2. nice article and clearly explained..., but any info about the implementation of OAuth in .net...? By using the library available in the below siet..?
    http://www.dotnetopenauth.net/

    ReplyDelete
  3. And if possible i need to known this implementation of captch for comments in blogger and presenting uris as plain-text.
    Thank you..

    ReplyDelete
  4. thanks Ruchi....your article helped me to implement facebook login in my website

    ReplyDelete
  5. How can I redirect from when user request the page.

    Great article.
    Keep it up.

    ReplyDelete
  6. thanks ruchi for integrate facebook in my website

    ReplyDelete
  7. If I login, I will see only my details, if my friend login he will see his.

    How can implement this.and get the details,name ,email,etc

    ReplyDelete
  8. Do u have sample code for Linkedin Login using asp.net?

    ReplyDelete
  9. Hi i am getting a error "The remote server returned an error: (400) Bad Request." on line of streamreader..can you pls help me out why i am getting such an error?i have tried making new application ,but in vein!

    please help!
    Thanks in Advance!

    ReplyDelete
  10. i am getting error when it redirect to facebook "Error
    Sorry, this feature isn't available right now: An error occurred while processing this request. Please try again later."

    ReplyDelete
  11. you can check it at this path "http://video.besttimepass.com/"

    ReplyDelete
  12. i m getting error invalid app id

    ReplyDelete
    Replies
    1. hii Ali you can create your aap in facebook and facebook will provide you app id. Follow this link
      http://developers.facebook.com/setup/

      Delete
  13. how to share website link to facebook..
    plz give some idea.or its related code in asp.net

    ReplyDelete
  14. Thank you so much..
    Nice Post!!!

    ReplyDelete