【问题标题】:401 Unauthorize even after FormsAuthentication.SetAuthCookie()401 未经授权,即使在 FormsAuthentication.SetAuthCookie() 之后
【发布时间】:2015-03-19 12:19:53
【问题描述】:

我正在尝试使用基本表单身份验证实现 ASP.NET MVC5 应用程序。 于是就有了我的登录方式:

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Login(string email, string password, bool? rememberMe)
    {
        if (email.IsNullOrWhiteSpace() || password.IsNullOrWhiteSpace())
        {
            return RedirectToAction("Index");
        }

        UserEntity user = new UserEntity() {Email = email, PasswordHash = password};
        var userFromDb = _userService.FindUser(user);
        if (userFromDb != null)
        {
            FormsAuthentication.SetAuthCookie(userFromDb.Name, rememberMe.GetValueOrDefault());

            var a = HttpContext.User.Identity.IsAuthenticated; //This is still false for some reson
            return RedirectToAction("Index", "User");
        }

        return RedirectToAction("Index");
    }

但是在重定向这个方法之后它给了我401 Unauthorized 错误。 也好像 HttpContext.User.Identity.IsAuthenticated 是假的。

您对为什么会这样以及如何解决有什么想法/建议吗?


UPD:我也有一个来自 auth 的 webconfig 概念,所以这不是原因

<authentication mode="Forms"> <forms loginUrl="~/Login/Index" /> </authentication>

【问题讨论】:

    标签: c# .net asp.net-mvc asp.net-mvc-5 forms-authentication


    【解决方案1】:

    我找到了原因。出于某种原因,在我的 webconfig 中有一行,它禁止 FormsAuthentication 模块

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

    因此,FormsAuthentiction 这一行不起作用,但如果我们将其注释掉或删除,一切都会按预期工作。

    【讨论】:

    • 这是因为 MVC5 默认不使用 FormsAuthentication。它使用 ASP.NET 标识,因此它删除了默认模板中的 FormsAuthentication。当您替换它时,您没有重新启用 FormsAuth。
    【解决方案2】:

    地点 将&lt;authentication mode="Forms" /&gt; 添加到&lt;system.web&gt; 中的 web.config 文件中,以触发其效果。

    【讨论】:

    • 这就是我要找的东西,谢谢!
    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2011-03-06
    • 2018-05-19
    • 2020-06-11
    • 2017-02-22
    • 2018-10-08
    相关资源
    最近更新 更多