MVC5 Forms authentication not working

2019-06-04 18:23发布

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.

1条回答
唯我独甜
2楼-- · 2019-06-04 19:10

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>
查看更多
登录 后发表回答