I'm trying to wrap my head around Forms Authentication in ASP.NET MVC. MVC 5 in my specific case, in case that matters.
My application doesn't use passwords, just an email address as username.
When debugging the Login
method, I can clearly see the model is valid and my (custom) MembershipProvider
validates the user as expected.
It then redirects to the provided returnUrl
(for purposes of testing, I have an AuthorizeAttribute
on /Home/About).
Sadly, I get thrown back to the Login
view immediately so it's obvious I'm missing a fundamental element to the whole process (and, by extension, fundamental insight into the whole auth/auth process, I must admit as I rarely play around with it).
The Login method:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if(ModelState.IsValid && Membership.ValidateUser(model.Email, ""))
{
FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return RedirectToLocal(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Email address unknown");
}
return View(model);
}
The LoginViewModel:
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
The pertinent part of the Web.config:
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
</system.web>
What am I not seeing? Where should I be looking?
You're setting your cookie using FormsAuthentication. If you're using MVC5, they removed that type of authentication with the [Authorize]
attribute.
Look for this in your web.config. Remove that line if you want to use FormsAuthentication.
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
You may want to read this about why Microsoft removed FormsAuthentication in MVC5 and how to use OWIN instead: http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx
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