2014-12-03 51 views
0

我對.NET和安全性很陌生。我選擇了實現Forms身份驗證(糾正我,如果我應該使用別的東西)。從我收集的互聯網上,我做了以下,但它不工作:MVC5表單身份驗證不起作用

的Web.config

<authentication mode="Forms"> 
    <forms loginUrl="~/Home/Index" timeout="30" /> 
</authentication> 

HTTPPost AJAX登錄方法:

[HttpPost] 
     public ActionResult Login(LoginInputModel loginModel) 
     { 
      if (ModelState.IsValid) 
      { 
       var success = UserService.Login(loginModel.Password, loginModel.Email); 
       if (success) 
       { 
        return Json(new { Url = Url.Action("Index","Home") }); 
       } 
       loginModel.ErrorMessages = "Failed to log in with these credentials. Please try again."; 
       return PartialView("Widgets/Login/_LoginInput", loginModel); 
      } 
      return PartialView("Widgets/Login/_LoginInput", loginModel); 
     } 

隨着UserService實際登錄碼等級:

public static bool Login(string password, string email) 
     { 
      var user = Connector.GetUserByCredentials(password, email); 
      if (user == null) return false; 
      FormsAuthentication.SetAuthCookie(email, false); // this line 
      SessionService.Delete(UserSessionKey); 
      SessionService.Store(UserSessionKey, UserMapper.DbUserToUser(user)); 
      return SessionService.HasKey(UserSessionKey); 
     } 

每當我登錄時,它的作品沒關係(它刷新頁面和我看到不同的內容),但是如果我然後導航到另一個頁面,我會再次重定向到登錄頁面。我(沒有)做錯了什麼?

如果您需要更多代碼,我很樂意發佈它。

+0

爲什麼你'<形式loginUrl = 「〜/首頁/索引」 超時= 「30」/>'?它應該是你的控制器的'Login()'方法,例如'/帳戶/登錄' – 2014-12-03 22:19:05

+0

首頁/索引是第一頁,包含一個登錄窗口小部件進入帳戶/登錄,所以如果我想重定向到登錄頁面,它應該是主頁/索引 – PoeHaH 2014-12-03 22:27:00

回答

11

當你說你正在使用MVC5時,你正在使用什麼版本的Visual Studio?您是否使用最初由默認嚮導創建的應用程序?

如果應用程序是由默認嚮導創建的,那麼默認情況下它將啓用ASP.NET身份,並且它將從處理中刪除FormsAuthentication模塊。如果您想繼續使用FormsAuth,那麼您必須從Forms.Authentication模塊的web.config中刪除「remove」鍵。

您需要刪除此行

<system.webServer> 
    <modules> 
     <remove name="FormsAuthentication" /> <----**** 
    </modules> 
</system.webServer> 
+0

這確實是一個問題: )我現在感到很蠢^^ – PoeHaH 2014-12-04 06:02:46

+1

@PoeHaH - 沒有必要,這是一種晦澀的......大多數人只是使用ASP.NET身份,並不會嘗試恢復到FormsAuthentication。 – 2014-12-04 06:08:50

+0

我是否應該留下表單身份驗證並轉到身份認證?有沒有一個很好的初學者教程,我可以如何讓自己的用戶數據庫使用Identity? – PoeHaH 2014-12-04 06:48:17