gpt4 book ai didi

c# - 为什么用户必须输入正确的凭据两次?

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:34 25 4
gpt4 key购买 nike

public ActionResult Login(CredentialsModel model)
{
authenticator.Authenticate(model.Username, model.Password);

if (authenticator.Authenticated)
{
return Redirect();
}
}

...

public class Authenticator : IAuthenticator
{
public bool Authenticated
{
get { return HttpContext.Current.User.Identity.IsAuthenticated; }
}

public void Authenticate(string username, string password)
{
var authenticated = FormsAuthentication.Authenticate(username, password);
if (authenticated)
FormsAuthentication.SetAuthCookie(username, false);
}

public void Logout()
{
FormsAuthentication.SignOut();
}
}

当上述操作方法向 Authenticate 方法提供一些有效凭据时,Authenticated 属性返回 false,这显然是错误的。

当操作方法第二次 提供一些凭据时,Authenticated 属性返回 true。

我怀疑这与上下文没有立即更新有关。我实际上设法通过在操作方法中使用 FormsAuthentication.Authenticate 的立即返回值来解决此错误,但我想知道为什么会出现此错误。

最佳答案

因为在与第一次调用一起发送的 HTTP 上下文中,用户 已通过身份验证(但之后的调用将正确进行)。在这一行之后:

var authenticated = FormsAuthentication.Authenticate(username, password);

您可能会看到 authenticated != Authenticated。为什么?来自 MSDN :

[HttpContext] Encapsulates all HTTP-specific information about an individual HTTP request.

这意味着它适用于请求(您的输入)而不是响应或 future 状态(您的输出)。如果您在 Controller 的方法中执行 SignOut(),您还会看到 HttpContext.Current.User.Identity.IsAuthenticated 仍然是 true

您可以为 Authenticate() 添加一个 bool 返回值:

public bool Authenticate(string username, string password)
{
var authenticated = FormsAuthentication.Authenticate(username, password);
if (authenticated)
FormsAuthentication.SetAuthCookie(username, false);

return authenticated:
}

将 Controller 中的 then 代码更改为:

if (authenticator.Authenticate(model.Username, model.Password))
{
return Redirect();
}

关于c# - 为什么用户必须输入正确的凭据两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526239/

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