【问题标题】:MVC5 Forms authentication not workingMVC5 表单身份验证不起作用
【发布时间】: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);
        }

每当我点击登录时,它都可以正常工作(它刷新页面并且我看到不同的内容),但如果我随后导航到另一个页面,我会再次被重定向到登录页面。我(没有)做错了什么?

如果您需要更多代码,我很乐意发布。

【问题讨论】:

  • 你为什么有&lt;forms loginUrl="~/Home/Index" timeout="30" /&gt;?它应该是控制器的 Login() 方法,例如/Account/Login
  • 首页/索引是第一个页面,包含一个登录小部件,可以转到帐户/登录,所以如果我想重定向到登录页面,它应该是首页/索引

标签: asp.net-mvc forms-authentication


【解决方案1】:

当您说您使用的是 MVC5 时,您使用的是哪个版本的 Visual Studio?您使用的是最初由默认向导创建的应用程序吗?

如果应用程序是由默认向导创建的,则默认情况下它启用 ASP.NET Identity,并从处理中删除 FormsAuthentication 模块。如果您想继续使用 FormsAuth,则必须从 Web.config 中删除 FormsAuthentication 模块的“删除”键。

您需要删除此行

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

【讨论】:

  • @PoeHaH - 没必要,这有点晦涩难懂...大多数人只是使用 ASP.NET Identity 而不会尝试恢复到 FormsAuthentication。
  • 我应该留下表单身份验证并转到身份验证吗?有没有一个很好的初学者教程如何让我自己的用户数据库使用 Identity?
猜你喜欢
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多