参见英文答案 >
Why new fb api 2.4 returns null email on MVC 5 with Identity and oauth 2?5个答案使用Facebook API v2.3,如果设置了以下设置,用户的电子邮件地址将返回到ExternalLoginCallback;
app.UseFacebookAuthentication(new FacebookAuthenticationOptions { AppId = "XXX",AppSecret = "XXX",Scope = { "email" } });
但是,任何只能针对v2.4(7月8日发布)的应用程序不再将电子邮件地址返回到ExternalLoginCallback。
我认为这可能与here所列的v2.4变更有关;
Declarative Fields
To try to improve performance on mobile networks,
Nodes and Edges in v2.4 requires that you explicitly request the
field(s) you need for your GET requests. For example,GET
no longer includes likes and comments by default,but
/v2.4/me/Feed
GET /v2.4/me/Feed?fields=comments,likes
will return the data. For more
details see the docs on how to request specific fields.
如何才能立即访问此电子邮件地址?
解决方法
要解决这个问题,我不得不从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; }
并获得FacebookAccessToken我扩展了ConfigureAuth;
app.UseFacebookAuthentication(new FacebookAuthenticationOptions { AppId = "XXX",Scope = { "email" },Provider = new FacebookAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken",context.AccessToken)); return Task.FromResult(true); } } });