我试图在Visual Studio 2013中的一个新的MVC 5项目中设置集成的OWIN Facebook身份验证。我已经按照本教程配置了应用和密钥:
但是,我在AccountController中从此调用中抛出NullReferenceException:
[AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
我已经检查了Fiddler的回应,并且得到了Facebook的成功回应,但仍然收到这个错误。响应如下所示:
{"id":"xxx","name":"xxx","first_name":"xxx","last_name":"xxx","link": "https:\/\/www.facebook.com\/profile.PHP?id=xxx","location":{"id":"xxx","name":"xxx"},"gender":"xxx","timezone":1,"locale":"en_GB","verified":true,"updated_time":"2013-10-23T10:42:23+0000"}
我在http和https调试时得到这个。我猜这是一个框架错误,但是迄今为止已经通过反射器来绘制了一个空白的诊断。
解决方法
这可能是身份OWIN扩展代码中的错误。我无法重现这个问题,因为我的Facebook有效载荷总是返回一个用户名字段在json,这是从你的fb响应中丢失。我不太清楚为什么不在那里
身份owin扩展方法中的代码对于身份的名称声明没有空值检查,与用户名字段相同。我们在内部提交了一个错误。
为了解决这个问题,您可以尝试使用以下代码替换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 }); } }