MVC5窗体身份验证不工作 [英] MVC5 Forms authentication not working

查看:131
本文介绍了MVC5窗体身份验证不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的.NET和安全性。我选择来实现窗体身份验证(纠正我,如果我应该使用别的东西)。从我收集到的互联网上,我做了以下,但它不工作:

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文件

Web.config

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

HTTPPost阿贾克斯登录方式:

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);
        }

随着UserService类实际登录code:

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?

如果你需要更多的code,我会很乐意将它张贴。

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

推荐答案

当你说你正在使用MVC5,你使用的是什么版本的Visual Studio?您是否使用最初是由一个默认的向导创建的应用程序?

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?

如果该申请被默认的向导创建的,则默认情况下它使ASP.NET身份,并删除从处理FormsAuthentication模块。如果你想使用FormsAuth那么你已经删除,以保持从web.config的FormsAuthentication模块删除键。

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.

您需要删除此行

<system.webServer>
    <modules>
        <remove name="FormsAuthentication" /> <----****
    </modules>
</system.webServer>

这篇关于MVC5窗体身份验证不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆