Asp.net-mvc – MVC Authorization – multiple login pages

asp.net-mvc

I have a the following methods in an MVC Controller which redirect to the login page when a user is not logged in.

[Authorize]
public ActionResult Search() {
  return View();
}

[Authorize]
public ActionResult Edit() {
  return View();
}

Is there a quick/easy/standard way to redirect the second action to a different login page other than the page defined in the web.config file?

Or do I have to do something like

public ActionResult Edit() {
  if (IsUserLoggedIn)
    return View();
  else 
     return ReturnRedirect("/Login2");
}

Best Answer

I think it is possible by creating a custom authorization filter:

public class CustomAuthorization : AuthorizeAttribute
{
    public string LoginPage { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.HttpContext.Response.Redirect(LoginPage);
        }
        base.OnAuthorization(filterContext);
    }
}

In your action:

[CustomAuthorization(LoginPage="~/Home/Login1")]
public ActionResult Search() 
{
  return View();
}

[CustomAuthorization(LoginPage="~/Home/Login2")]
public ActionResult Edit() 
{
  return View();
}