Asp.net-Mvc

MVC 5 Owin Facebook Auth 導致空引用異常

  • October 24, 2013

我正在嘗試在 Visual Studio 2013 的新 MVC 5 項目中設置集成的 OWIN Facebook 身份驗證。我已按照本教程配置了應用程序和密鑰:

<http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on>

但是,我在 AccountController 中的此呼叫中拋出了 NullReferenceException:

   [AllowAnonymous]
   public async Task&lt;ActionResult&gt; 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 響應中缺少該欄位。我不太確定為什麼它不存在。

identity owin 擴展方法中的程式碼沒有對與使用者名欄位相同的身份名稱聲明進行空檢查。我們已經在內部送出了一個錯誤。

為了解決這個問題,您可以嘗試用以下程式碼替換您的 ExternalLoginCallback 方法:

  [AllowAnonymous]
   public async Task&lt;ActionResult&gt; 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 });
       }
   }

當 facebook/google 沒有返回使用者名時,程式碼會將預設使用者名設置為空。

引用自:https://stackoverflow.com/questions/19564479