Request.IsAuthenticated always returning false MVC

I created new project and I did setup routes and other necessary functions, now it was turn for form authentication.
I follow up all necessary steps, required to validate the user like creating cookie etc like below:

var userData = JsonConvert.SerializeObject(serializeModel);
var expiryDate = model.RememberMe ? DateTime.Now.AddDays(14) : DateTime.Now.AddDays(1);
var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, expiryDate, model.RememberMe, userData);
var cookiestr = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr) { Path = FormsAuthentication.FormsCookiePath };
HttpContext.Response.Cookies.Add(cookie);

Did build project, succeeded without any error,  now its time to test it. I used simple method to test the if request is authenticated or not using following simple way:

if(User.Identity.IsAuthenticated)
{
  return RedirectToAction("Dashboard");
}

What was the problem?

But condition was false and It didn’t happen to take user to dashboard page, I double checked the code and everything was fine. After wasting an hour eventually I went to web.config
where I found I forgot to add authentication method, I didn’t tell system how I manage to validate the user.

Solution (whew)

So solution was very simple, we just need to define authenticate method in web.config and it should work.

 <system.web>
  <authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
  </authentication>
 </system.web>

Again did build the solution and yeah now its working perfectly fine 🙂

Leave a Reply