加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 09:14:28 所属栏目:asp.Net 来源:网络整理
导读:我正在玩认证和授权以准备一些任务.我创建了两个页面:Login.aspx和Default.aspx.在配置文件中,我为表单设置了身份验证,并拒绝了未经身份验证的用户访问: authentication mode="Forms" forms name="aaa" defaultUrl="~/Login.aspx" / /authentication autho
我正在玩认证和授权以准备一些任务.我创建了两个页面: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提供程序接受的有效值,或将该令牌放入URL中.您可以重定向到您的心脏内容,因为cookie显然会与用户一起用于将来的请求.

来自MSDN(em添加):

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读