简体   繁体   English

如何在MVC中使用Facebook C#SDK获得生日(和其他字段)的权限

[英]How to get permission for birthday (and other fields) using Facebook C# SDK in MVC

I am building an MVC 4 website that allows users to login via Facebook. 我正在建立一个MVC 4网站,该网站允许用户通过Facebook登录。 All this works like a charm out-of-the-box. 所有这一切都像开箱即用的魅力。

But now I am stuck at getting the user's birthday from Facebook. 但是现在,我一直坚持从Facebook获取用户的生日。 I have installed the latest version of the Facebook C# SDK (6.1.4) from Nuget. 我已经从Nuget安装了最新版本的Facebook C#SDK(6.1.4)。 I have set up my app in Facebook to request permission for user_birthday. 我已经在Facebook中设置了我的应用,以请求user_birthday的许可。 When I look at the Login Dialog Preview birthday is in the list of permissions. 当我查看“登录对话框”时,预览生日在权限列表中。

When I run my MVC application and login via my own facebook account I get my birthday in the response, but as soon as I login using a different account, no birthday is passed back and there is also no Login Dialog where the user can grant my app permission to use the birthday field. 当我运行我的MVC应用程序并通过我自己的facebook帐户登录时,我会在响应中得到生日,但是一旦我使用其他帐户登录,就不会再传回生日,也没有用户可以授予我的登录对话框。应用程序使用生日字段的权限。 Below is the complete code of my ExternalLoginCallback() action: 以下是我的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 
            });
    }
}

I hope somebody can tell me what I am doing wrong here. 我希望有人可以告诉我我在这里做错了什么。 I have Googled for two days no but somehow I haven't been able to find the right answer. 我已经用Google搜索了两天了,但是不知为何我找不到正确的答案。 Or maybe I am just to dumb to understand it. 也许我只是愚蠢地理解它。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Erwin 欧文

You have to make sure that you add the birthday to the scope! 您必须确保将生日添加到范围! Default it is not grapped by the facebookAuthenticationvar fbAuthOpt = new FacebookAuthenticationOptions(); 默认情况下,它不会被facebookAuthenticationvar 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);

Later on I grap this with "urn:facebook:birthday". 稍后,我用“ urn:facebook:birthday”来了解。

This post has a fix that worked great for me! 这篇文章的修复对我非常有用! He created a custom facebook provider, there you can create your scope requesting permissions and then the querystring to get the info. 他创建了一个自定义Facebook提供程序,您可以在其中创建请求权限的范围,然后创建查询字符串以获取信息。

http://savvydev.com/authenticating-facebook-users-with-mvc-4-oauth-and-obtaining-scope-permissions/ http://savvydev.com/authenticating-facebook-users-with-mvc-4-oauth-and-obtaining-scope-permissions/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM