我正在尝试使用Microsoft OWIN OAuth库将Facebook身份验证实现到现有的ASP.NET MVC 5应用程序中,但无法找到如何获取用户电子邮件地址的方法。注册如下:
var options = new FacebookAuthenticationOptions
{
AppId = "YYY",
AppSecret = "ZZZ"
};
options.Scope.Add("public_profile");
options.Scope.Add("email");
app.UseFacebookAuthentication(options);
范围email
已添加到选项中。
在身份验证时,在控制器的ExternalLoginCallback
方法中,使用此代码email
为空:
AuthenticateResult authResult = await authenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity externalIdentity = authResult.Identity;
string email = externalIdentity.FindFirstValue(ClaimTypes.Email);
也试过这个无济于事:
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
var email = loginInfo.Email;
从Facebook返回的Json数据似乎不包含电子邮件地址:
{"id":"989197284440871","first_name":"Martin","gender":"male","last_name":"Stauf\u010d\u00edk","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/989197284440871\/","locale":"cs_CZ","name":"Martin Stauf\u010d\u00edk","timezone":2,"updated_time":"2014-10-18T16:14:08+0000","verified":true}
Facebook没有返回地址或者代码中缺少什么问题?任何提供的帮助将不胜感激。
谢谢。
答案 0 :(得分:0)
要回答我自己的问题,我刚刚升级了应用程序以使用最新的组件MVC 5.2.3和OWIN 3.0.1,现在身份验证正在运行。获取电子邮件地址的代码是:
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
var email = loginInfo.Email;
...
}
这是在Visual Studio中创建的新ASP.NET MVC Web项目附带的默认代码。无论问题是什么,现在都已解决。
答案 1 :(得分:-1)
我测试了下面的代码并且它可以正常工作
var loginInformation = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
if (loginInformation != null && loginInformation.Identity != null &&
loginInformation.Identity.IsAuthenticated)
{
var claimsIdentity = loginInformation.Identity;
var providerKeyClaim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
string providerKey = providerKeyClaim.Value;
string issuer = providerKeyClaim.Issuer;
string name = claimsIdentity.FindFirstValue(ClaimTypes.Name);
string emailAddress = claimsIdentity.FindFirstValue(ClaimTypes.Email);
}