Search code examples
asp.net-mvc-3http-redirectauthenticationreturnurl

MVC3 Redirect after login


Been trying to put together an mvc login page that will redirect back to the original page that required authorization based on other stack overflow posts.

Redirect with

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
  filterContext.Result = new RedirectToRouteResult(
                             new RouteValueDictionary 
                               {
                                   { "action", "login" },
                                   {"ReturnUrl", filterContext.HttpContext.Request.RawUrl},
                                   { "controller", "mycontroller" }
                               });
}

login page view has

@Html.Hidden("returnUrl", ViewContext.HttpContext.Request.Params["returnurl"])

located inside the form. I originally used ViewContext.HttpContext.Request.Url.PathAndQuery based on another forum post, but that included the entire url.

Inside controller I have

[HttpPost]
public ActionResult Login(MyModel model)
{
   if (loginisValid)
      return Redirect(model.ReturnUrl);
   else
      return View();
}

but that does nothing but return the orignal page even though it's hitting the Redirect. I've also tried RedirectToAction and RedirectToRoute, but those give errors. I'm testing this on my index page which is at localhost/admin/mycontroller. So model.ReturnUrl currently contains "/admin/mycontroller". What should I be changing to make this work?


Solution

  • It turned out all this code was correct. However, I didn't put

    [RequireHttps(Order=0)] 
    

    on top of my controller so it never stored cookies correctly and after redirecting back to my index page it was failing authorization again.