Facebook成功登录后,ExternalLoginConfirmation返回null

Dav*_*ave 1 c# facebook asp.net-mvc-5

在MVC 5模板中实现Facebook登录,已添加了应用ID和密码。

最初登录失败,因为它返回null

public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    // Crashes on this line
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
}
Run Code Online (Sandbox Code Playgroud)

搜索后遇到一个解决方案,该解决方案说用此替换现有的ExternalLoginCallback方法

[AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
        if (result == null || result.Identity == null)
        {
            return RedirectToAction("Login");
        }

        var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
        if (idClaim == null)
        {
            return RedirectToAction("Login");
        }

        var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);
        var name = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", "");

        // Sign in the user with this external login provider if the user already has a login
        var user = await UserManager.FindAsync(login);
        if (user != null)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToLocal(returnUrl);
        }
        else
        {
            // If the user does not have an account, then prompt the user to create an account
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.LoginProvider = login.LoginProvider;
            return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = name });
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,该问题已解决,但是当我尝试关联您的Facebook帐户时。您已成功通过Facebook进行身份验证。请在下面输入此站点的用户名,然后单击“注册”按钮以完成登录。

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
    {
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Manage");
        }

        if (ModelState.IsValid)
        {
            // Here comes the error System.NullReferenceException: Object reference not set to an instance of an object.

            var info = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return View("ExternalLoginFailure");
            }
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await UserManager.AddLoginAsync(user.Id, info.Login);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToLocal(returnUrl);
                }
            }
            AddErrors(result);
        }

        ViewBag.ReturnUrl = returnUrl;
        return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

在调试用户名时,也就无法弄清其抛出异常的原因。

小智 5

我认为当GetExternalLoginInfoSync返回到null时。

我遇到了同样的问题,这就是我如何设法修复它并从Facebook获得电子邮件。

  • 在更新NuGet Pacakges之后
    • Microsoft.Owin 到版本 3.1.0-rc1
    • Microsoft.Owin.Security 到版本 3.1.0-rc1
    • Microsoft.Owin.Security.Cookies 到版本 3.1.0-rc1
    • Microsoft.Owin.Security.OAuth 到版本 3.1.0-rc1
    • Microsoft.Owin.Security.Facebook 到版本 3.1.0-rc1

然后将以下代码添加到Identity Startup类中

var facebookOptions = new FacebookAuthenticationOptions()
        {
            AppId = "your app id",
            AppSecret = "your app secret",
            BackchannelHttpHandler = new FacebookBackChannelHandler(),
            UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
            Scope = { "email" }
        };

        app.UseFacebookAuthentication(facebookOptions);
Run Code Online (Sandbox Code Playgroud)

这是定义类FacebookBackChannelHandler()

using System;
using System.Net.Http;

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

        return await base.SendAsync(request, cancellationToken);
    }
}
Run Code Online (Sandbox Code Playgroud)