Asp.net-Mvc-5

MVC 5 & ASP.NET Identity - 實現混亂

  • July 25, 2016

我正在創建一個新的 Web 應用程序,它將使用MVC 5Entity Framework Database First Approach編寫。我還想使用ASP.Net Identity來處理成員資格、身份驗證、授權等。

我已經閱讀了很多關於 Web 上的 ASP.Net Identity 及其工作原理的內容,但是,我仍在學習這個主題。

當我在 Visual Studio 2013 中創建我的 MVC 5 應用程序並查看帳戶控制器時,我的第一直覺是我不喜歡我所看到的,即,一個名為“ ApplicationDbContext ”的****DbContext被引用。我不喜歡這樣的原因是因為我更喜歡將我的 DbContext 保留在我的解決方案中的適當項目中,即,在我的模型層中,它遵循關注點分離邏輯。

此外,開箱即用的 MVC 5 項目使用 Entity Framework Code First 創建預設數據庫和表來儲存使用者、角色等。

因為我必須使用現有的數據庫和現有的 User 表,所以這種方法不適合我的需要。

我仍然想為我的應用程序使用最新的 ASP.Net 標識,因為它看起來有很多好處,因此,我發現這篇文章剝離了很多實體框架程式碼,但仍然將 OWIN 支持的身份驗證轉換為 ASP.NET MVC。

http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux

使用上面的教程,這是我的帳戶控制器的****HttpPost 登錄方法

   [HttpPost]
   [AllowAnonymous]
   public ActionResult Login(LoginViewModel model, string returnUrl)
   {
       if (ModelState.IsValid)
       {
           //Calling my own custom Account Service which validates users login details
           var user = _AccountService.VerifyPassword(model.UserName, model.Password, false);
           if (user)
           {
               var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

               //ToDo: Manually adding Role, but will pull from db later
               identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));

               AuthenticationManager.SignIn(new AuthenticationProperties
               {
                   IsPersistent = model.RememberMe
               }, identity);

               return RedirectToAction("Index", "MyDashboard");
           }
           else
           {
               ModelState.AddModelError("", "Invalid username or password.");
           }
       }

       return View(model);
   }

在我以前的 MVC 應用程序中,我通常推出自己的自定義成員資格,當使用者登錄站點並通過身份驗證時,我會將任何其他使用者詳細資訊(例如 userID、DOB 等)儲存在FormsAuthenticationTicket的****UserData字元串中。

由於上面的程式碼沒有使用FormsAuthentication,而是使用OWIN CookieAuthentication,我不確定如何儲存這些額外的使用者數據。

因此,我對我遇到的問題有幾個問題。

  1. 如何以我在 FormsAuthentication 中使用的方式儲存使用者 ID 或任何其他使用者數據(DOB 等)?這是通過向身份添加聲明來完成的嗎?
  2. 考慮到我首先將實體框架數據庫與現有數據庫一起使用,上述使用 ASP.Net Identity/OWIN 的方法是否正確?
  3. 我是否應該使用帳戶控制器中使用的開箱即用程式碼,即 UserManager、ApplicationUser、ApplicationDbContext 等,並將其連接到我現有的數據庫中?

如果我的問題令人困惑,我深表歉意,我想我只是有點不確定在我的最新項目中嘗試使用 ASP.Net Identity 時應該使用什麼方法。

任何回饋將不勝感激。

謝謝。

  1. 新的 Katana Cookie 中間件支持聲明。這就是使它比表單身份驗證 cookie 更好的原因;聲明對任何鍵/值對進行建模,並且可以將其儲存在身份驗證 cookie 中。有關更多詳細資訊,請參閱此文章:

http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

2 & 3) 至於身份數據的儲存,如果您需要使用現有表,那麼您可能無法使用 Microsoft 的 EF 提供的類。相反,您將獨自實現 IUserStore 和您的應用程序需要的所有其他商店介面。我不確定是否值得更改您已經用來儲存使用者數據的內容。

請記住,OWIN/Katana 部分與身份儲存是分開的。

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