【发布时间】:2014-12-04 06:34:23
【问题描述】:
我对 .NET 和安全性非常陌生。我选择实现表单身份验证(如果我应该使用其他东西,请纠正我)。根据我在互联网上收集的信息,我做了以下操作,但它不起作用:
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);
}
每当我点击登录时,它都可以正常工作(它刷新页面并且我看到不同的内容),但如果我随后导航到另一个页面,我会再次被重定向到登录页面。我(没有)做错了什么?
如果您需要更多代码,我很乐意发布。
【问题讨论】:
-
你为什么有
<forms loginUrl="~/Home/Index" timeout="30" />?它应该是控制器的Login()方法,例如/Account/Login -
首页/索引是第一个页面,包含一个登录小部件,可以转到帐户/登录,所以如果我想重定向到登录页面,它应该是首页/索引
标签: asp.net-mvc forms-authentication