【问题标题】:User.Identity.IsAuthenticated returns false sometimesUser.Identity.IsAuthenticated 有时会返回 false
【发布时间】:2023-03-15 07:28:01
【问题描述】:

我正在使用 asp.net 4.0 和 Form auth。 要检查用户是否经过身份验证,我使用 User.Identity.IsAuthenticated。 大多数时候它工作得很好,但我不知道如何,有时即使用户有身份验证它也会返回 false。 我的 web.config:

<authentication mode="Forms">
    <forms name=".xyz" loginUrl="~/" timeout="120" protection="All" path="/" slidingexpiration=true/>
</authentication>

在 global.asax 中:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    if (authCookie == null)
    {
        return;
    }
    FormsAuthenticationTicket authTicket = null;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }
    if (authTicket == null)
    {
        return;
    }
    string[] roles = authTicket.UserData.Split(new char[] { '|' });
    FormsIdentity id = new FormsIdentity(authTicket);
    GenericPrincipal principal = new GenericPrincipal(id, roles);

    Context.User = principal;
}

在登录页面中:

FormsAuthenticationTicket authTick = new FormsAuthenticationTicket(1, email.Text, DateTime.Now, DateTime.Now.AddDays(360), true, password.Text, FormsAuthentication.FormsCookiePath);
string encriptTicket = FormsAuthentication.Encrypt(authTick);

HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encriptTicket);
authCookie.Expires = DateTime.Now.AddDays(360);
Response.Cookies.Add(authCookie);

我也每 5 分钟使用一次 ajax 请求。保持会话活动,这也会重置身份验证超时,因为slidingexpiration 值。 我不知道它有什么问题。有时在同一会话和同一分钟内,它会为一个页面返回 false,即使它为所有其他页面返回 true。我从来没有遇到过这个错误,但我的访问者声称这个问题。

【问题讨论】:

  • 您尝试过 Context.Request.IsAuthenticated 吗?
  • 没有。它更可靠吗?

标签: asp.net forms-authentication iprincipal


【解决方案1】:

我发现了问题。问题在于 www.address.com 和 address.com 之间的区别。 www 版本伪装成一个子域并创建新的会话和身份验证。如果用户在没有 www 前缀的情况下服务器重定向到 www 地址,则会发生错误。我会尝试 url 重写来解决它。

【讨论】:

  • 对我来说这是一个我忘记的 Web.config 转换。
  • @DaviddCeFreitas,您能否提供有关您的解决方案的更多详细信息
  • @ebramtharwat,我有一个生产/开发 web.config.debug 类型的转换文件,它在构建后更改了值。尝试在 Visual Studio 浏览器中展开 web.config 文件,或者如果您有其他 web.config.* 文件可能会在构建时转换或更改您的值,请检查您的项目文件夹。
猜你喜欢
  • 2020-10-04
  • 2013-10-30
  • 2019-07-10
  • 2019-01-27
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
相关资源
最近更新 更多