form验证小例
发布日期:2022-02-05 18:27:35 浏览次数:15 分类:技术文章

本文共 1717 字,大约阅读时间需要 5 分钟。

webconfig配置如下

    <authentication mode="Forms" >
  <forms name=".SecurityDemo" loginUrl="login.aspx">//.SecurityDemo为cookie名,
  </forms>
    </authentication>

 <authorization>

            <deny users="?"/> //拒绝所有匿名用户
            <allow roles="admins"/>//允许管理级别用户访问
   </authorization>
  <location path="admin.aspx">
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>
登陆时的后置代码 login.aspx

 private void btnLoginBetter_Click(object sender, System.EventArgs e)

  {
   if (this.tbName.Text == "admin" && this.tbPass.Text == "admin")
   {
    FormsAuthenticationTicket ticket = new     FormsAuthenticationTicket(1,this.tbName.Text,DateTime.Now,DateTime.Now.AddMinutes(30),this.PersistCookie.Checked,"User");
    //创建一个验证票据
    string cookieStr = FormsAuthentication.Encrypt(ticket); //进行加密
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,cookieStr);//创建一个cookie,cookie名为web.config设置的名,值为加密后的数据cookieStr,
    if (this.PersistCookie.Checked)//判断用户是否选中保存cookie
    cookie.Expires = ticket.Expiration;//获取cookie过期时间
    cookie.Path = FormsAuthentication.FormsCookiePath;//设置cookie保存路径
    Response.Cookies.Add(cookie);
    string strRedirect;
    strRedirect = Request["ReturnUrl"];//取出返回url
    if (strRedirect == null)
     strRedirect = "Default.aspx";
    Response.Redirect(strRedirect,true);
   }
   else
   {
    Response.Write("<script>alert('帐号或密码错误!');self.location.href='02login.aspx'</script>");
   }
  }
通过验证后的后置代码 Default.aspx

  private void Page_Load(object sender, System.EventArgs e)

  {
   this.lbUser.Text = User.Identity.Name;
   if (User.IsInRole("Admin"))//判断角色
    this.lbSf.Text = "Admin";
   else
    this.lbSf.Text = "User";
  }
  private void btnLogout_Click(object sender, System.EventArgs e)
  {
   FormsAuthentication.SignOut();//注销票
   Response.Redirect("login.aspx",true);返回login.aspx页面
  }
 

转载地址:https://blog.csdn.net/lisong58420/article/details/1842037 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:一套.net窗体身份验证方案(解决了防止用户重复登陆,session超时等问题)
下一篇:C#时间操作

发表评论

最新留言

很好
[***.229.124.182]2024年04月14日 05时55分43秒