form驗證小例

來源:互聯網
上載者:User

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頁面
  }
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.