Facebook签名验证,.NET代码

时间:2010-09-27 21:21:40

标签: facebook authentication cookies

是2010年9月,我正在尝试更新我们网站上的Facebook连接集成。

我需要验证由Facebook代码设置的auth cookie。我正在关注来自http://developers.facebook.com/docs/guides/web

的PHP示例

请检查C#代码:

    public static Dictionary<string, string> ParseCookie(HttpCookie fbCookie)
    {
        if (fbCookie == null)
            return null;

        string value = fbCookie.Value.Substring(1, fbCookie.Value.Length - 2);
        SortedDictionary<string, string> sargs = new SortedDictionary<string, string>();

        foreach (string pair in value.Split('&'))
        {
            string[] keyvalue = pair.Split('=');
            sargs.Add(keyvalue[0], keyvalue[1]);
        }

        string sid = sargs["sig"] ?? string.Empty;
        sargs.Remove("sig");

        string payload = string.Empty;
        foreach (KeyValuePair<string, string> pair in sargs)
        {
            payload += pair.Key + "=" + pair.Value;
        }

        if (string.IsNullOrEmpty(payload) || DataFormatter.GetMD5Hash(payload + Settings.ApplicationSecret).ToUpper() != sid.ToUpper())
            return null;

        return sargs.ToDictionary(pair => pair.Key, pair => pair.Value);
    }

DataFormatter.GetMD5Hash方法是:

    public static string GetMD5Hash(string key)
    {
        StringBuilder result = new StringBuilder();
        MD5 md5 = new MD5CryptoServiceProvider();
        foreach (byte b in md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)))
            result.Append(b.ToString("X2"));

        return result.ToString();
    }

问题在于我的md5永远不会与Facebook的sig匹配

    DataFormatter.GetMD5Hash(payload + Settings.ApplicationSecret).ToUpper() != sid.ToUpper()

始终为True

请帮助找到解决方案。

由于

1 个答案:

答案 0 :(得分:1)

    public static Dictionary<string, string> ParseCookie(HttpCookie fbCookie)
    {
        if (fbCookie == null)
            return null;

        string value = fbCookie.Value.Substring(1, fbCookie.Value.Length - 2);
        SortedDictionary<string, string> sargs = new SortedDictionary<string, string>();

        foreach (string pair in value.Split('&'))
        {
            string[] keyvalue = pair.Split('=');
            if (keyvalue.Length != 2)
                continue;
            sargs.Add(keyvalue[0], keyvalue[1]);
        }

        string sid = sargs["sig"] ?? string.Empty;
        sargs.Remove("sig");

        string payload = sargs.Aggregate(string.Empty, (current, pair) => current + (pair.Key + "=" + HttpUtility.UrlDecode(pair.Value)));


        if (string.IsNullOrEmpty(payload) || DataFormatter.GetMD5Hash(payload + Settings.ApplicationSecret).ToUpper() != sid.ToUpper())
            return null;

        return sargs.ToDictionary(pair => pair.Key, pair => pair.Value);
    }