我對.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);
}
每當我登錄時,它的作品沒關係(它刷新頁面和我看到不同的內容),但是如果我然後導航到另一個頁面,我會再次重定向到登錄頁面。我(沒有)做錯了什麼?
如果您需要更多代碼,我很樂意發佈它。
爲什麼你'<形式loginUrl = 「〜/首頁/索引」 超時= 「30」/>'?它應該是你的控制器的'Login()'方法,例如'/帳戶/登錄' – 2014-12-03 22:19:05
首頁/索引是第一頁,包含一個登錄窗口小部件進入帳戶/登錄,所以如果我想重定向到登錄頁面,它應該是主頁/索引 – PoeHaH 2014-12-03 22:27:00