gpt4 book ai didi

ASP.NET:在代码中验证用户

转载 作者:行者123 更新时间:2023-12-01 07:48:55 25 4
gpt4 key购买 nike

我正在尝试使用身份验证和授权来为某些任务做准备。我创建了两个页面:Login.aspx 和 Default.aspx。在配置文件中,我已将身份验证设置为表单并拒绝未经身份验证的用户访问:

<authentication mode="Forms">
<forms name="aaa" defaultUrl="~/Login.aspx" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>

然后我编写了一些简单的代码来验证我在 Login.aspx 中的用户:
protected void Page_Load(object sender, EventArgs e)
{
GenericIdentity identity = new GenericIdentity("aga", "bbb");
Context.User = new GenericPrincipal(identity, new String[] { "User" }); ;
Response.Redirect("~/Default.aspx");
}

当我运行它时,重定向不会发生。而是一遍又一遍地调用 Login.aspx,因为用户未经过身份验证(每次加载时 Context.User.Identity.IsAuthenticated 为 false)。我究竟做错了什么?

最佳答案

Context.User仅设置当前请求的主体。重定向发生后,当前请求结束,新请求再次以未覆盖的主体开始(显然未经过身份验证)。因此,设置 Context.User实际上并没有验证任何东西。

使用 FormsAuthentication.SetAuthCookie() 将用户的 cookie 设置为 FormsAuthentication 提供程序接受的有效值,或将 token 放入 URL。您可以重定向到您心中的内容,因为 cookie 显然会与用户保持联系以备将来的请求。

来自 MSDN(已添加):

With forms authentication, you can use the SetAuthCookie method when you want to authenticate a user but still retain control of the navigation with redirects.



如前所述,这并不一定需要 cookie - 这个名称有点误导,因为如果 FormsAuthentication 处于无 cookie 模式,它仍然可以通过 URL 工作:

The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection, or to the URL if CookiesSupported is false.

关于ASP.NET:在代码中验证用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1439746/

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