i need a login widget thar appears on every page:
- when user logs in he is redirected to the same page
- if login fails user redirects to the same page and see error message
widget is rendered with Html.RenderAction
when submitting login form, i take current page url (with java script) and sent it to server – so I can redirect user to the same page after login
public ActionResult Login(string email, string password, string returnUrl)
{
if (userService.AuthenticateUser(email, password))
{
FormsAuthentication.SetAuthCookie(email, true);
if (!string.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
return RedirectToAction("Default");
}
else
{
ModelState.AddModelError("login_fail", "login failed");
if (!string.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
return View();
}
}
The problem is when errors happens: i need to show them to user but after redirect from Login action all ModelState data is lost (with errors).
The question is: how can I implement login widget to fulfill all above requirments?
Is AJAX an acceptable solution? This way you always stay on the same page and don’t need to redirect. Another option would be to store the error message in
TempDataso that you can fetch it and show it on the redirected page:Also for security reasons it is important to verify that
returnUrlbelongs to your domain before redirecting or a hacker could create a link and areturnUrlpointing to some spoofing site that looks exactly the same as your and which tricks the user into putting his username and password once again. The default ASP.NET MVC template in Visual Studio suffers from this same vulnerability.