c# - 如何使用 Facebook 取消授权回调

标签 c# asp.net facebook

我正在使用 ASP.NET 我想实现 FB 解除授权的监听器。

我从FB服务器获取signed_request参数。 如何使用 C# 解密它?

谢谢!

最佳答案

不确定您是否正确...但我引用了 Facebook C# SDK 并执行了此操作:

Deauth.aspx:

protected void Page_Load(object sender, EventArgs e)
{

    if (!String.IsNullOrEmpty(Request["signed_request"]))
    {

        string signed_request = Request["signed_request"];

        Dictionary<string, Facebook.JSONObject> jsonDict = new Dictionary<string, Facebook.JSONObject>();
        if (Helper.FacebookAPI.ValidateSignedRequest(signed_request, out jsonDict))
        {

            if (jsonDict.ContainsKey("user_id"))
            {
                long FacebookId = jsonDict["user_id"].Integer;
                // delete code
            }

        }
    }
}

然后我的 Facebook Helper 类如下所示:

namespace Helper {
public static class FacebookAPI
{
    public static Dictionary<string, Facebook.JSONObject> DecodePayload(string payload)
    {
        var encoding = new UTF8Encoding();
        var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
        var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
        var json = encoding.GetString(base64JsonArray);
        var jObject = Facebook.JSONObject.CreateFromString(json);            
        return jObject.Dictionary;
    }


    public static bool ValidateSignedRequest(string VALID_SIGNED_REQUEST, out Dictionary<string, Facebook.JSONObject> json)
    {
        string applicationSecret = ConfigurationManager.AppSettings["Secret"];
        string[] signedRequest = VALID_SIGNED_REQUEST.Split('.');
        string expectedSignature = signedRequest[0];
        string payload = signedRequest[1];

        json = DecodePayload(payload);

        // Attempt to get same hash
        var Hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(payload), UTF8Encoding.UTF8.GetBytes(applicationSecret));
        var HmacBase64 = ToUrlBase64String(Hmac);

        return (HmacBase64 == expectedSignature);
    }


    private static string ToUrlBase64String(byte[] Input)
    {
        return Convert.ToBase64String(Input).Replace("=", String.Empty)
                                            .Replace('+', '-')
                                            .Replace('/', '_');
    }

    private static byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody)
    {
        using (var hmacAlgorithm = new HMACSHA256(keyBody))
        {
            hmacAlgorithm.ComputeHash(dataToSign);
            return hmacAlgorithm.Hash;
        }
    }


    public static string SerializeDict(Dictionary<string, Facebook.JSONObject> jsonDict)
    {
        // serialize the dictionary
        DataContractSerializer serializer = new DataContractSerializer(jsonDict.GetType());

        using (StringWriter sw = new StringWriter())
        {
            using (XmlTextWriter writer = new XmlTextWriter(sw))
            {
                // add formatting so the XML is easy to read in the log
                writer.Formatting = Formatting.Indented;

                serializer.WriteObject(writer, jsonDict);

                writer.Flush();

                return sw.ToString();
            }
        }
    }



    public static string GetAuthToken()
    {

        string appId = ConfigurationManager.AppSettings["AppId"];
        string secret = ConfigurationManager.AppSettings["Secret"];

        string url = String.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", appId, secret);

        string[] token = HttpGetData(url).Split('=');
        return token[1];
    }

    public static string HttpGetData(string url)
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            return (reader.ReadToEnd());
        }
    }
    public static string HttpPostData(string url, string nameValuePair)
    {

        HttpWebRequest request = WebRequest.Create(url + "&" + nameValuePair) as HttpWebRequest;
        request.Method = WebRequestMethods.Http.Post;
        try
        {
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                return (reader.ReadToEnd());
            }
        }
        catch (WebException ex)
        {
            return ex.Message;
        }
    }
}}

关于c# - 如何使用 Facebook 取消授权回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4546884/

相关文章:

c# - 带有制表符分隔文本文件的 StreamReader

ios - Facebook iOS SDK 版本 4.0.1 中的 FBSDKAppInviteDialog 邀请成功发送,但没有收到通知

c# - 将进度保存到文本文件 C#

c# - 从 C# 发送邮件时使用 To 或 CC - 在性能方面哪个更好?

c# - 如何查看通过编译表达式树创建的委托(delegate)的反汇编?

javascript - 第二次单击浅灰色弹出窗口时,Azure Media Player 不播放视频

php - Facebook API(通过 PHP): Post to Feed?

javascript - 如何通过 Facebook Graph Api 获取用户的 friend 在生日当天在用户墙上发布的帖子?

c# - Automapper 使用简单注入(inject)器 (Ioc) 将依赖项注入(inject)自定义类型转换器

c# - 如何在 C# 中解析字符串(以逗号和结尾的符号,即 "3,246,928-")?