FormsAuthentication MVC4

2019-07-14 18:58发布

I am trying to get simple Forms Authentication setup with an MVC4 website.

In App_start/FilterConfig.cs:

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

In Web.config:

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

In Controllers/AccountController:

[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;
}

Now when I debug this in Visual Studio, which lands on the base URL (say localhost:1111/) it correctly redirects to the login page (localhost:1111/Account/Login?ReturnUrl=%2f)

However, if I just modify the URL back to localhost:1111/ and hit enter, I am able to access the site. In this scenario, httpcontext.current.user.identity.name is still my Windows NT login name. I have made sure to call FormsAuthentication.Logout to clear the cookie. If I login, and set "PersistCookie" to true, don't call FormsAuthentication.Logout, and just reboot my debug session, I am still initially re-directed to the Login page, but can just circumvent by modifying the URL. So, same results with and without the cookie. How do I make this work with strictly Forms Authentication? What am I doing wrong?

1条回答
趁早两清
2楼-- · 2019-07-14 19:36

You need to add filter to check that user is authenticated/Authorized or not.

1. Add following attribute

public class AuthorizeWithSessionAttribute : AuthorizeAttribute {

protected override bool AuthorizeCore(HttpContextBase httpContext)
{

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

    return false;

return base.AuthorizeCore(httpContext);
}

}

2. Set the session after SetAuthCookie()

FormsAuthentication.SetAuthCookie(user.UserName, false);

Session["XYZSession"] = "Set name/parameter";

3. Set attribute before controller

[AuthorizeWithSessionAttribute]

public class XYZController : Controller

查看更多
登录 后发表回答