Here is a small class in C# to validate the Facebook cookie (fbsr_APPID)
Here I have used Jayrock’s json C# library to handle the json strings in C#.
public string Base64Decode(string str)
{
str = str.Replace("-", "+");
str = str.Replace("_", "/");
str = str.PadRight(str.Length + (4 - str.Length % 4) % 4, '=');
byte[] decbuff = Convert.FromBase64String(str);
return Encoding.UTF8.GetString(decbuff);
}
public List validateFacebookCookie(string signedRequest, string secret, string appId)
{
List userData = new List();
string encodedSig = signedRequest.Split(new char[] { '.' })[0];
string payLoad = signedRequest.Split(new char[] { '.' })[1];
string sig = Base64Decode(encodedSig);
string payLoad_decoded = Base64Decode(payLoad);
Jayrock.Json.JsonObject data = (Jayrock.Json.JsonObject)Jayrock.Json.Conversion.JsonConvert.Import(payLoad_decoded);
if (Convert.ToString(data["algorithm"]).ToUpper() == "HMAC-SHA256")
{
System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(secret));
hmac.ComputeHash(Encoding.UTF8.GetBytes(payLoad));
byte[] hashSecret = hmac.Hash;
string hashString = Encoding.UTF8.GetString(hashSecret);
if (sig == hashString)
{
//valid login
//set cookie
System.Net.WebClient wc = new System.Net.WebClient();
string accessToken = wc.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" + secret + "&redirect_uri=&code=" + Convert.ToString(data["code"]));
accessToken = HttpUtility.ParseQueryString(accessToken)["access_token"];
string userId = Convert.ToString(data["user_id"]);
//1. user id
userData.Add(userId);
//2. access token
userData.Add(accessToken);
}
else
{
throw new Exception("Invalid authentication, Please re-login.");
}
}
else
{
throw new Exception("Invalid authentication, Please re-login.");
}
return userData;
}
signedRequest is value of the facebook cookie that is being created for the application using the facebook js framework.
secret is your application secret.
appid is your application id. ( signedRequest is the value of cookie named “fbsr_APPID”)