我的问题非常相似this,但我想我需要更进一步。
Facebook说“数据作为已签名的请求传递给您的应用程序.cigned_request参数是确保您收到的数据是Facebook发送的实际数据的简单方法。”
用户登录我的asp c#MVC站点并单击“注册”后,redirect-url为http://site/account/register。此时(帐户/注册控件的帖子),我想使用签名请求收集用户的信息,以便我可以在本地注册我的网站。我无法弄清楚如何访问facebook提供的数据。
$data = json_decode(base64_url_decode($payload), true);
C#中的等价物是什么? Facebook在帖子中传递了什么类型的变量/数据?我如何访问“$ payload”?
[HttpPost]
public ActionResult RegisterFacebook(RegisterFacebookModel model)
{
Facebook.FacebookSignedRequest sr = Facebook.FacebookSignedRequest.Parse("secret", model.signed_request);
return View(model);
}
答案 0 :(得分:8)
以下是我们在Facebook C#SDK中使用的代码。如果您使用我们的sdk,则无需手动执行此操作,但如果您需要在此处自行执行此操作,则可以:
/// <summary>
/// Parses the signed request string.
/// </summary>
/// <param name="signedRequestValue">The encoded signed request value.</param>
/// <returns>The valid signed request.</returns>
internal protected FacebookSignedRequest ParseSignedRequest(string signedRequestValue)
{
Contract.Requires(!String.IsNullOrEmpty(signedRequestValue));
Contract.Requires(signedRequestValue.Contains("."), Properties.Resources.InvalidSignedRequest);
string[] parts = signedRequestValue.Split('.');
var encodedValue = parts[0];
if (String.IsNullOrEmpty(encodedValue))
{
throw new InvalidOperationException(Properties.Resources.InvalidSignedRequest);
}
var sig = Base64UrlDecode(encodedValue);
var payload = parts[1];
using (var cryto = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(this.AppSecret)))
{
var hash = Convert.ToBase64String(cryto.ComputeHash(Encoding.UTF8.GetBytes(payload)));
var hashDecoded = Base64UrlDecode(hash);
if (hashDecoded != sig)
{
return null;
}
}
var payloadJson = Encoding.UTF8.GetString(Convert.FromBase64String(Base64UrlDecode(payload)));
var data = (IDictionary<string, object>)JsonSerializer.DeserializeObject(payloadJson);
var signedRequest = new FacebookSignedRequest();
foreach (var keyValue in data)
{
signedRequest.Dictionary.Add(keyValue.Key, keyValue.Value.ToString());
}
return signedRequest;
}
/// <summary>
/// Converts the base 64 url encoded string to standard base 64 encoding.
/// </summary>
/// <param name="encodedValue">The encoded value.</param>
/// <returns>The base 64 string.</returns>
private static string Base64UrlDecode(string encodedValue)
{
Contract.Requires(!String.IsNullOrEmpty(encodedValue));
encodedValue = encodedValue.Replace('+', '-').Replace('/', '_').Trim();
int pad = encodedValue.Length % 4;
if (pad > 0)
{
pad = 4 - pad;
}
encodedValue = encodedValue.PadRight(encodedValue.Length + pad, '=');
return encodedValue;
}
您可以在此处找到完整的源代码:http://facebooksdk.codeplex.com/SourceControl/changeset/view/f8109846cba5#Source%2fFacebook%2fFacebookApp.cs
答案 1 :(得分:1)
根据您的评论,您似乎仍在寻找FB正在发送的响应。我相信它包含在HttpContext Request对象的Form集合中。因此,从您指定为重定向的页面,您应该可以从以下位置获取它:
HttpContext.Current.Request.Form( “signed_request”)
希望这有助于解决问题。我还在学习,所以这可能不是最好的解决方案。
感谢, 杰森
答案 2 :(得分:1)
以下是使用Facebook SDK
的方法var parsedSignedRequest = FacebookSignedRequest.Parse(FacebookApplication.Current, signed_request);