asp.net身分識別驗證和授權

來源:互聯網
上載者:User
asp.net

今天閑著無聊.想起來了ASP.NET身分識別驗證.感覺良好.貼出下列代碼:
login.aspx HTML代碼

 
 1<%@ Page language="c#" Codebehind="02Login.aspx.cs" AutoEventWireup="false" Inherits="身分識別驗證._02Login" %>
 2<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
 3<HTML>
 4    <HEAD>
 5        <title>02Login</title>
 6        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
 7        <meta name="CODE_LANGUAGE" Content="C#">
 8        <meta name="vs_defaultClientScript" content="javascript">
 9        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
10    </HEAD>
11    <body MS_POSITIONING="GridLayout">
12        <form id="Form1" method="post" runat="server">
13            <FONT face="宋體">
14                <TABLE id="Table1" style="Z-INDEX: 102; LEFT: 152px; WIDTH: 446px; POSITION: absolute; TOP: 80px; HEIGHT: 72px"
15                    cellSpacing="1" cellPadding="1" width="446" border="1">
16                    <TR>
17                        <TD>
18                            <asp:label id="Label1" runat="server">使用者名稱稱:</asp:label></TD>
19                        <TD>
20                            <asp:textbox id="tbName" runat="server" Width="183px"></asp:textbox></TD>
21                        <TD>
22                            <asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" ErrorMessage="使用者名稱不可為空!" ControlToValidate="tbName"></asp:requiredfieldvalidator></TD>
23                    </TR>
24                    <TR>
25                        <TD>
26                            <asp:label id="Label2" runat="server">密碼:</asp:label></TD>
27                        <TD>
28                            <asp:textbox id="tbPass" runat="server" Width="183px"></asp:textbox></TD>
29                        <TD>
30                            <asp:requiredfieldvalidator id="RequiredFieldValidator2" runat="server" ErrorMessage="密碼不可為空!" ControlToValidate="tbPass"></asp:requiredfieldvalidator></TD>
31                    </TR>
32                    <TR>
33                        <TD><FONT face="宋體">是否儲存Cookie</FONT></TD>
34                        <TD>
35                            <asp:checkbox id="PersistCookie" runat="server"></asp:checkbox></TD>
36                        <TD></TD>
37                    </TR>
38                </TABLE>
39                <asp:button id="btnLoginBetter" style="Z-INDEX: 101; LEFT: 288px; POSITION: absolute; TOP: 240px"
40                    runat="server" Width="78px" Text="登入"></asp:button>
41                <asp:HyperLink id="HyperLink1" style="Z-INDEX: 103; LEFT: 456px; POSITION: absolute; TOP: 240px"
42                    runat="server" NavigateUrl="Default.aspx">HyperLink</asp:HyperLink></FONT>
43        </form>
44    </body>
45</HTML>
login.aspx.cs代碼如下

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 HTML代碼

<body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <FONT face="宋體">
                <asp:Label id="Label1" style="Z-INDEX: 106; LEFT: 224px; POSITION: absolute; TOP: 72px" runat="server">使用者名稱稱:</asp:Label>
                <asp:Label id="Label2" style="Z-INDEX: 102; LEFT: 220px; POSITION: absolute; TOP: 136px" runat="server">身份:</asp:Label>
                <asp:Label id="lbUser" style="Z-INDEX: 103; LEFT: 350px; POSITION: absolute; TOP: 79px" runat="server"></asp:Label>
                <asp:Label id="lbSf" style="Z-INDEX: 104; LEFT: 355px; POSITION: absolute; TOP: 133px" runat="server"></asp:Label>
                <asp:Button id="btnLogout" style="Z-INDEX: 105; LEFT: 261px; POSITION: absolute; TOP: 192px"
                    runat="server" Text="登出" Width="101px"></asp:Button></FONT>
        </form>
    </body>
後置代碼

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";
  }

  Web Form設計器產生的程式碼#region Web Form設計器產生的程式碼
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 該調用是 ASP.NET Web Form設計器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
 
  /**//// <summary>
  /// 設計器支援所需的方法 - 不要使用代碼編輯器修改
  /// 此方法的內容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.btnLogout.Click += new System.EventHandler(this.btnLogout_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void btnLogout_Click(object sender, System.EventArgs e)
  {
   FormsAuthentication.SignOut();//登出票
   Response.Redirect("login.aspx",true);返回login.aspx頁面
  }


webconfig配置如下
    <authentication mode="Forms" >
  <forms name=".SecurityDemo" loginUrl="login.aspx">//.SecurityDemo為cookie名,
  </forms>
    </authentication>

 <authorization>
            <deny users="?"/> //拒絕所有匿名使用者
            <allow roles="admins"/>//允許管理層級使用者訪問
   </authorization>
自我感覺ASP寫多了,一般是用session進行判斷使用者是否合法,但在一個ASP.NET項目中使用身分識別驗證,基本上所有頁面都要驗證才能訪問,感覺有點遷強.但可以在web.config頁面對指定的版面設定許可權,設定代碼如下
  <location path="admin.aspx">
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>
如果只有幾個版面設定如上代碼,感覺還可以接受.但頁面多了豈不是要把人累死呀..
可能是小的項目做多了,大項目沒接觸過.請高手給指點具體用途呀.不甚感激



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.