We have an internal ASP.NET MVC application that requires a logon. Log on works great and does what's expected. We have a session expiration of 5 minutes. After sitting on a single page for that period of time, the user has lost the session. If they attempt to refresh the current page or browse to another, they will get a log on page.
My question is (after reloggin in) where to tell MVCto redirect to their (refresh/browse) attempt instead of getting HOME controller page always ?
Normally this should happen automatically. When an anonymous user hits a protected resource (he is anonymous because his session expired), the FormsAuthentication module intercepts this requests and redirects to the loginUrl you registered in your web.config by appending a ReturnUrl query string parameter pointing to the protected resource.
So if for example you configured ~/Account/LogOn to be your logon url, and the anonymous user attempts to hit the ~/Foo/Bar protected resource he will be redirected to ~/Account/LogOn?ReturnUrl=%2FFoo%2FBar.
Then he will be presented with a login page where he will input his credentials and submit the form to the [HttpPost] LogOn action on the Account controller. The credentials will be validated and if valid, a new forms authentication cookie will be generated and the user redirected to the initially requested protected resource.
Here's the respective code from the LogOn action:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Notice how the user is redirected either to the default Home/Index or to the returnUrl parameter upon successful authentication.
Now of course all this story that I told here is true for the default ASP.NET MVC template created by Visual Studio. If for some reason you have modified this template this might explain the behavior you are observing.
In any case the thing to remember from my answer is that if you are using Forms Authentication, the module will pass as ReturnUrl query string parameter the initially requested protected resource to the configured logon page. So it's up to you to redirect the user to this page upon successful authentication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With