gpt4 book ai didi

asp.net-mvc - AuthenticationManager.SignIn 上的 HttpContext.Current.User.Identity

转载 作者:行者123 更新时间:2023-12-02 00:59:43 27 4
gpt4 key购买 nike

我正在使用 ASP.Net Identity 来管理我的用户。

我在调用以下命令后发现:

AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);

当我检查用户当前是否通过 HttpContext.Current.User.Identity.IsAuthenticated 进行身份验证时,它返回 false

我通过执行以下操作设法让它返回 true:

FormsAuthentication.SetAuthCookie(model.UserName, false);

是否可以将 HttpContext.Current.User.Identity.IsAuthenticated 设置为 true

最佳答案

您不必要地与系统作对。

AuthenticationManager.SignIn 采用身份参数,您可以将其用于当前请求的其余部分,该请求应该非常短。

var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
Debug.WriteLine(identity.IsAuthenticated); //true
Debug.WriteLine(this.Request.IsAuthenticated); //false

手头请求的目的是简单地对用户进行身份验证。你不应该做更多的事情,如果有的话,然后返回响应/做重定向。

即使您刚刚(成功)验证了用户,this.Request.IsAuthenticated==false 的原因是因为此值是由 FormsAuthenticationModule 设置的在初始阶段(AuthenticateRequest)请求管道。

FormsAuthenticationModule将查找 auth-cookie 并根据在那里找到的信息进行身份验证 (IsAuthenticated=true)。

这一切都发生在您点击 Controller 中的操作之前,因此如果请求未通过身份验证,则可以将其短路。

因此,简单地在您的登录操作中对用户进行身份验证不会更改此值,因为为时已晚。从请求管道的角度来看,所有这些操作都是附加/重新验证将在下一个请求期间由 auth 模块使用的 auth-cookie。

这又是为什么我们通常会立即重定向,以便在下一个请求中由 auth 模块更新值。

关于asp.net-mvc - AuthenticationManager.SignIn 上的 HttpContext.Current.User.Identity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30087620/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com