Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC5 Forms authentication not working

I'm very new to .NET and security. I've chosen to implement Forms authentication (correct me if I should use something else). From what I gathered on the internet, I did the following, but it's not working:

Web.config

<authentication mode="Forms">
   <forms loginUrl="~/Home/Index" timeout="30" />
</authentication>

HTTPPost ajax Login method:

 [HttpPost]
        public ActionResult Login(LoginInputModel loginModel)
        {
            if (ModelState.IsValid)
            {
                var success = UserService.Login(loginModel.Password, loginModel.Email);
                if (success)
                {
                    return Json(new { Url = Url.Action("Index","Home") });
                }
                loginModel.ErrorMessages = "Failed to log in with these credentials. Please try again.";
                return PartialView("Widgets/Login/_LoginInput", loginModel);
            }
            return PartialView("Widgets/Login/_LoginInput", loginModel);
        }

With actual login code in UserService class:

  public static bool Login(string password, string email)
        {
            var user = Connector.GetUserByCredentials(password, email);
            if (user == null) return false;
            FormsAuthentication.SetAuthCookie(email, false); // this line
            SessionService.Delete(UserSessionKey);
            SessionService.Store(UserSessionKey, UserMapper.DbUserToUser(user));
            return SessionService.HasKey(UserSessionKey);
        }

Whenever I hit login, it works okay (it refreshes the page and I see different content), but if I then navigate to another page, I get redirected to the login page again. What am I (not) doing wrong?

If you need more code, I'll be happy to post it.

like image 731
PoeHaH Avatar asked Jun 05 '26 20:06

PoeHaH


1 Answers

When you say you're using MVC5, what version of Visual Studio are you using? Are you using an application that was originally created by a default wizard?

If the application was created by the default wizard, then by default it enables ASP.NET Identity, and it removes the FormsAuthentication module from processing. If you want to keep using FormsAuth then you have to remove the "remove" key from the web.config for the FormsAuthentication module.

You need to remove this line

<system.webServer>
    <modules>
        <remove name="FormsAuthentication" /> <----****
    </modules>
</system.webServer>
like image 117
Erik Funkenbusch Avatar answered Jun 07 '26 09:06

Erik Funkenbusch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!