在asp net中从facebook获取用户电子邮件

lev*_*ter 6 c# asp.net oauth facebook-oauth

我正在尝试从Facebook获取用户名和用户电子邮件.我阅读了很多关于这个主题的信息,这是我的最终代码,仅在我的facebook app管理员帐户上有效:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {

        /*Other external login options*/

         var FacebookOptions = new FacebookAuthenticationOptions()
                {
                    AppId = "My App Id",
                    AppSecret = "My App Secret",
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                    BackchannelHttpHandler = new FacebookBackChannelHandler(),
                    UserInformationEndpoint = "https://graph.facebook.com/v2.7/me?fields=id,name,email"
                };


    }
}
public class FacebookBackChannelHandler : HttpClientHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
        }

        return await base.SendAsync(request, cancellationToken);
    }
}
public class AccountController : Controller
{
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        /*my sign in code that works on my facebook app admin account*/
    }  
}    
Run Code Online (Sandbox Code Playgroud)

我得到的每一个账户 loginInfo.Email都等于null.

developers.facebook.com我有:

批准的项目

当有人点击"使用Facebook登录"时,他会收到以下消息:

第一个Facebook登录页面

如果我点击"查看您提供的信息",我会得到:

查看您提供的信息

我错过了什么?为什么不起作用?

lev*_*ter 5

终于找到了答案!所有这一切需要做的是添加Scope = { "email" }FacebookOptions而这解决了这个问题!

我的代码现在:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {

        /*Other external login options*/

         var FacebookOptions = new FacebookAuthenticationOptions()
                {
                    AppId = "My App Id",
                    AppSecret = "My App Secret",
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                    BackchannelHttpHandler = new FacebookBackChannelHandler(),
                    Scope = { "email" },
                    UserInformationEndpoint = "https://graph.facebook.com/v2.7/me?fields=id,name,email"
                };
    }
}
Run Code Online (Sandbox Code Playgroud)

其余代码保持不变.如果此问题返回,我只为案例添加了错误页面:

public class AccountController : Controller
{
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if(loginInfo.Email == null)
        {
             return RedirectToAction("FacebookError", "Account");
        }
        /*my sign in code*/
    }  
}   
Run Code Online (Sandbox Code Playgroud)