【问题标题】:FormsAuthentication MVC4表单验证 MVC4
【发布时间】:2013-09-11 16:35:31
【问题描述】:

我正在尝试使用 MVC4 网站进行简单的表单身份验证设置。

在 App_start/FilterConfig.cs 中:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new HandleErrorAttribute());
   filters.Add(new AuthorizeAttribute());
}

在 Web.config 中:

<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" name=".ASPFORMSAUTH" />
</authentication>
  <authorization>
      <deny users="?" />
</authorization>

在控制器/帐户控制器中:

[AllowAnonymous]
public ActionResult Login()
{
    return View("~/Views/MyAccountViews/Login.cshtml");
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    ActionResult retVal = View("~/Views/MyAccountViews/Login.cshtml", model); 

    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            retVal = RedirectToAction("Index", "Home");
        } 
    }

    return retVal;
}

现在,当我在 Visual Studio 中调试它时,它位于基本 URL(比如 localhost:1111/)上,它正确地重定向到登录页面(localhost:1111/Account/Login?ReturnUrl=%2f)

但是,如果我只是将 URL 修改回 localhost:1111/ 并回车,我就可以访问该站点。在这种情况下,httpcontext.current.user.identity.name 仍然是我的 Windows NT 登录名。我确保调用 FormsAuthentication.Logout 来清除 cookie。如果我登录并将“PersistCookie”设置为 true,不要调用 FormsAuthentication.Logout,而只是重新启动我的调试会话,我最初仍会被重定向到登录页面,但可以通过修改 URL 来规避。因此,使用和不使用 cookie 的结果相同。如何使用严格的表单身份验证进行这项工作?我做错了什么?

【问题讨论】:

  • 您是否检查过 web.config 设置
  • 如果你没有使用提供的 simpleMembership,你应该关闭它:

标签: asp.net-mvc asp.net-membership forms-authentication


【解决方案1】:

您需要添加过滤器以检查用户是否经过身份验证/授权。

1.添加以下属性

公共类 AuthorizeWithSessionAttribute : AuthorizeAttribute {

protected override bool AuthorizeCore(HttpContextBase httpContext)
{

if (httpContext.Session == null || httpContext.Session["XYZSession"] == null)

    return false;

return base.AuthorizeCore(httpContext);
}

}

2。在 SetAuthCookie() 之后设置会话

FormsAuthentication.SetAuthCookie(user.UserName, false);

Session["XYZSession"] = "设置名称/参数";

3。在控制器之前设置属性

[AuthorizeWithSessionAttribute]

公共类 XYZController : 控制器

【讨论】:

  • 谢谢。上述答案有效,但仍有一个问题。为什么 Request.IsAuthenticated 还在使用 Windows 身份验证?
  • 抱歉回复晚了,Request.IsAuthenticated 适用于 Windows、Passport、Forms 或我们自己的自定义方案身份验证,请阅读此链接:Click here
猜你喜欢
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多