如何在 C# 中为 Canvas signed_request 解码 OAuth 2.0? [英] How to decode OAuth 2.0 for Canvas signed_request in C#?

查看:21
本文介绍了如何在 C# 中为 Canvas signed_request 解码 OAuth 2.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用示例此处,但我无法解码有效负载.Facebook 文档指出,signed_request 中的第二个参数是 base64url 编码的 JSON 对象.在 PHP 中,payload 使用 json_decode 解码:

I'm able to successfully validate the signed request for a Facebook canvas app using the example here, but I'm unable to decode the payload. The Facebook documentation states that the 2nd parameter in signed_request is a base64url encoded JSON object. In PHP the payload is decoded using json_decode:

$data = json_decode(base64_url_decode($payload), true);

C# 中的等价物是什么?

What is the equivalent in C#?

推荐答案

以下内容应该对您有所帮助..

The following should help you out..

(注意:JObject 引用来自 JSON.NET,可通过 http://james.newtonking.com/projects/json-net.aspxhttp://json.codeplex.com/)

(Note: The JObject reference is from JSON.NET available via http://james.newtonking.com/projects/json-net.aspx and http://json.codeplex.com/)

使用的命名空间:

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq; // JSON.NET project 

代码:

public Dictionary<string,string> 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 = JObject.Parse(json);

        var parameters = new Dictionary<string, string>();
        parameters.Add("user_id", (string)jObject["user_id"] ?? "");
        parameters.Add("oauth_token", (string)jObject["oauth_token"] ?? "");
        var expires = ((long?) jObject["expires"] ?? 0);
        parameters.Add("expires", expires > 0 ? expires.ToString() : "") ;
        parameters.Add("profile_id", (string)jObject["profile_id"] ?? "");

        return parameters;
    }

这是我在 FaceSharp 中使用的.. 希望它有帮助

It is what I'm using in FaceSharp.. hope it helps

这篇关于如何在 C# 中为 Canvas signed_request 解码 OAuth 2.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆