从ASP.NET MVC 5中的Facebook v2.4 API访问OAuth ExternalLoginCallback中的电子邮件地址

Sta*_*ams 23 asp.net-mvc facebook oauth asp.net-mvc-5

使用Facebook API的v2.3,如果设置了以下内容,则会在回调时返回用户的电子邮件地址ExternalLoginCallback;

app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
    AppId = "XXX",
    AppSecret = "XXX",
    Scope = { "email" }
});
Run Code Online (Sandbox Code Playgroud)

但是,任何只能针对v2.4(7月8日发布)的应用程序不再将电子邮件地址返回给ExternalLoginCallback.

我认为这可能与此处列出的v2.4更改有关;

声明字段

要尝试提高移动网络的性能,v2.4中的节点和边缘要求您明确请求GET请求所需的字段.例如,GET /v2.4/me/feed默认情况下不再包含喜欢和评论,但 GET /v2.4/me/feed?fields=comments,likes会返回数据.有关更多详细信息,请参阅有关如何请求特定字段的文档.

我现在如何访问此电子邮件地址?

Sta*_*ams 57

要解决这个问题,我必须从nuget 安装Facebook SDK for .NET并分别查询电子邮件地址.

ExternalLoginCallback方法中,我添加了一个条件来填充Facebook Graph API中的电子邮件地址;

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

if (loginInfo == null)
{
    return RedirectToAction("Login");
}

// added the following lines
if (loginInfo.Login.LoginProvider == "Facebook")
{
    var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
    var access_token = identity.FindFirstValue("FacebookAccessToken");
    var fb = new FacebookClient(access_token);
    dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
    loginInfo.Email = myInfo.email;
}
Run Code Online (Sandbox Code Playgroud)

为了得到FacebookAccessToken我的延伸ConfigureAuth;

app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
    AppId = "XXX",
    AppSecret = "XXX",
    Scope = { "email" },
    Provider = new FacebookAuthenticationProvider
    {
        OnAuthenticated = context =>
        {
            context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
            return Task.FromResult(true);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @Yovav查看[api](https://developers.facebook.com/docs/graph-api/reference/user).它说你必须列出你想要的所有字段,所以我猜你是否把请求更改为`/ me?fields = email,birthday`你会收到回复中的电子邮件和生日. (4认同)

Ole*_*vik 14

在MVC 6(Asp.net Core 1.0)中,通过在startup.cs中配置FacebookAuthentication,如下所示:

         app.UseFacebookAuthentication(options =>
            {
                options.AppId = Configuration["Authentication:Facebook:AppId"];
                options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                options.Scope.Add("email");
                options.UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name";
            });
Run Code Online (Sandbox Code Playgroud)

我可以收到电子邮件.即:

   var info = await _signInManager.GetExternalLoginInfoAsync();
   var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
Run Code Online (Sandbox Code Playgroud)