I'm trying to convert this PHP cookie parsing snippet into C#, but my PHP is a bit rusty. It's taken from a facebook SDK sample.
<?php
define('FACEBOOK_APP_ID', 'your application id');
define('FACEBOOK_SECRET', 'your application secret');
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
echo 'The ID of the current user is ' . $cookie['uid'];
?>
This is what I have so far, but its not quite right:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
HttpCookie cookie = GetCookie();
IsLoggedIn = cookie != null;
}
private HttpCookie GetCookie()
{
// based on the php example at http://developers.facebook.com/docs/authentication/
HttpCookie cookie = Request.Cookies["fbs_" + FacebookClientId];
StringBuilder payload = new StringBuilder();
if (cookie != null)
{
foreach (string key in cookie.Values.Keys)
{
if (key != "sig")
{
payload.Append(key + "=" + cookie.Values[key]);
}
}
string sig = cookie.Values["sig"];
if (sig == GetMD5Hash(payload.ToString()))
{
return cookie;
}
}
return null;
}
public string GetMD5Hash(string input)
{
MD5CryptoServiceProvider cryptoServiceProvider = new MD5CryptoServiceProvider();
byte[] bytes = Encoding.UTF8.GetBytes(input);
bytes = cryptoServiceProvider.ComputeHash(bytes);
StringBuilder s = new StringBuilder();
foreach (byte b in bytes)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}
The one part I'm not sure about is parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
. From what I can tell its creating an array out of the trimmed cookie value. Can anyone provide some assistance?