Rectangle 27 0

c Custom Authentication and ASP.NET MVC?


<authentication mode="Forms">
     <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
FormsAuthentication
[Authorize]
public ActionResult Index()
{
    return View();
}
[HttpPost]
public ActionResult Login(User model, string returnUrl)
{
        //Validation code

        if (userValid)
        {
             FormsAuthentication.SetAuthCookie(username, false);
        }
}
public ActionResult LogOff()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Home");
}

Add the AuthorizeAttribute attribute to the action method declaration, as shown below,

Configuring Forms Authentication in web.config

Do I have to put [Authorize] on every Controller method in my entire app? I only want to open up two controller methods to anonymous users (~/Account/Login GET and POST). Seems like there should be a better way. Do this require a filter? custom attribute? Thanks for your help. +1

Login Post Action: Set Authentication cookie if user is valid

To restrict access to a view :

You can use Forms Authentication in conjuction with Authorize attibute as follows,

Note
Rectangle 27 0

c Custom Authentication and ASP.NET MVC?


GlobalFilters.Filters.Add(new LegacyAuthorize());
public class LegacyAuthorize : AuthorizeAttribute
{
  public override void OnAuthorization(HttpActionContext actionContext)
  {
    if (HttpContext.Current.Session["User"] == null)
      base.HandleUnauthorizedRequest(actionContext);
  }
}

Overriding the Authorize attribute can be dangerous especially if only validating session. Session Id is not re-generated, which can lead to session hijack via XSS etc. blog.securityps.com/2013/06/ and support.microsoft.com/en-us/kb/899918

Then in your global.asax you'd have something like this:

You probably want to have a custom authorization filter. Here's an example: Custom filters in MVC. You can then apply this filter globally on app start (using RegisterGlobalFilters).

Note
Rectangle 27 0

c Custom Authentication and ASP.NET MVC?


formsauthentication.setauthcookie("username")

After this any action with the [Authorize] keyword will allow the current user in.

Everything you could do in forms you can do in MVC, just set the session variable in the controller login action.

Note