Friday, May 27, 2011

ASP.NET FaceBook Login UserControl

http://www.eggheadcafe.com/tutorials/aspnet/fca40a96-aa44-4956-8382-447bf53f6035/aspnet-facebook-login-usercontrol.aspx

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FacebookLogin
{
    public partial class FBLogin : System.Web.UI.UserControl
    {
         public static string FaceBookAppKey = ConfigurationManager.AppSettings["facebookAppKey"];

        protected void Page_Load(object sender, EventArgs e)
         {
             if(String.IsNullOrEmpty( FaceBookAppKey ))
                throw new InvalidOperationException("You must have a valid Facebook App Key in AppSettings element \"facebookAppKey\"");

             if (Request.Cookies["fbs_" + FaceBookAppKey] == null)
            {
                lblMessage.Text = "Not logged in.";
                 return// No cookie returned from Facebook!!
            }


            string cookie = Request.Cookies["fbs_" + FaceBookAppKey].Value;
                cookie = cookie.Replace("\""""); //fix Facebook bug...
                NameValueCollection facebookValues = HttpUtility.ParseQueryString(cookie);

                  // send an http-request to facebook using the token from the cookie
                 //and parse the JSON response
                string json = GetFacebookUserJSON(facebookValues["uid"], facebookValues["access_token"]);
                Hashtable jsonHash = (Hashtable) JSON.JsonDecode(json);

                 //ok, let's actually read some data from FB response
                string facebookName = jsonHash["name"as string;
                string firstName = jsonHash["first_name"as string;
                string lastName = jsonHash["last_name"as string;
                string facebookId = jsonHash["id"as string;
                string email = jsonHash["email"as string;
                     //We explicitly requested email (see fb-button)
            lblMessage.Text = "Welcome, " + firstName + " " + lastName + " [" + email + "]";

             // Can store name, email etc. in db here, get user profile, store info in Session, etc.
        }

         /// <summary>
        /// sends http-request to Facebook and returns the response string
        /// </summary>
        private static string GetFacebookUserJSON(string userid, string access_token)
        {
            string url = string.Format("https://graph.facebook.com/{0}?access_token={1}&fields=email,first_name,last_name", userid, access_token);
            WebClient wc = new WebClient();
            string s = wc.DownloadString(url);
             wc.Dispose();
             return s;
        }
    }
}

No comments:

Post a Comment