如何在MVC中使用Facebook c# SDK获得生日(和其他字段)的权限
本文关键字:生日 其他 字段 权限 SDK MVC Facebook | 更新日期: 2023-09-27 18:02:38
我正在构建一个MVC 4网站,允许用户通过Facebook登录。所有这些都像开箱即用的魅力。
但是现在我无法从Facebook获取用户的生日。我已经从Nuget安装了最新版本的Facebook c# SDK(6.1.4)。我已经在Facebook上设置了我的应用程序来请求user_birthday的权限。当我看到登录对话框预览生日是在权限列表。
当我运行我的MVC应用程序并通过我自己的facebook帐户登录时,我得到我的生日在响应中,但只要我使用不同的帐户登录,没有生日传递回来,也没有登录对话框,用户可以授予我的应用程序使用生日字段的权限。下面是我的ExternalLoginCallback()操作的完整代码:
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
// Get the Facebook access token
if (result.ExtraData.Keys.Contains("accesstoken"))
{
Session["facebooktoken"] = result.ExtraData["accesstoken"];
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
var client = new FacebookClient(Session["facebooktoken"].ToString());
dynamic response = client.Get("me", new { fields = "gender, birthday" });
return View("ExternalLoginConfirmation",
new RegisterExternalLoginModel
{
UserName = result.UserName,
FullName = result.ExtraData["name"],
DateOfBirth = DateTime.ParseExact(response["birthday"], "MM/dd/yyyy", CultureInfo.InvariantCulture),
ExternalLoginData = loginData
});
}
}
我希望有人能告诉我我在这里做错了什么。我已经在谷歌上搜索了两天了,但不知怎么的,我还是没能找到正确的答案。也可能是我太笨了,看不懂。
任何帮助都将是非常感激的。
Erwin您必须确保将生日添加到作用域中!fbAuthOpt = new FacebookAuthenticationOptions();
fbAuthOpt.Scope.Add("email");
fbAuthOpt.Scope.Add("user_birthday");
fbAuthOpt.AppId = "";
fbAuthOpt.AppSecret = "";
fbAuthOpt.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
fbAuthOpt.Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
var claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
};
app.UseFacebookAuthentication(fbAuthOpt);
后来我用"urn:facebook:birthday"来抓这个