鲨丁鱼.net技术小栈

这里讨论.net的web和form开发,还有其它关于WEB开发和安全的全部知识点,顺带一些经典的有意思的杂文!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

基于窗体的/Cookie 身份验证示例

Posted on 2006-01-13 10:16  King0502  阅读(164)  评论(0编辑  收藏  举报

Login.aspx
-----------------------------
<%@ Import Namespace="System.Web.Security " %>

<html>
 

  <script language="C#" runat=server>

    void Login_Click(Object sender, EventArgs E) {

      // authenticate user: this samples accepts only one user with
      // a name of jdoe@somewhere.com and a password of 'password'

      if ((UserEmail.Value == "jdoe@somewhere.com") && (UserPass.Value == "密码")) {
        FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked);
      }
      else {
        Msg.Text = "凭据无效:请再试一次";
      }
    }

  </script>

  <body>

    <form runat=server>

      <h3><font face="宋体">登录页</font></h3>

      <table>
        <tr>
          <td>电子邮件:</td>
          <td><input id="UserEmail" type="text" runat=server/></td>
          <td><ASP:RequiredFieldValidator ControlToValidate="UserEmail" Display="Static" ErrorMessage="*" runat=server/></td>
        </tr>
        <tr>
          <td>密码:</td>
          <td><input id="UserPass" type=password runat=server/></td>
          <td><ASP:RequiredFieldValidator ControlToValidate="UserPass" Display="Static" ErrorMessage="*" runat=server/></td>
        </tr>
        <tr>
          <td>持久的 Cookie:</td>
          <td><ASP:CheckBox id=PersistCookie runat="server" /> </td>
          <td></td>
        </tr>
      </table>

      <asp:button text="登录" OnClick="Login_Click" runat=server/>

      <p>

      <asp:Label id="Msg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat=server />

    </form>
  </body>

</html>


-----------------------------
Default.aspx

<%@ Import Namespace="System.Web.Security " %>

<html>
 

  <script language="C#" runat=server>

    void Page_Load(Object Src, EventArgs E ) {

      Welcome.Text = "Hello, " + User.Identity.Name;
    }

    void Signout_Click(Object sender, EventArgs E) {

      FormsAuthentication.SignOut();
      Response.Redirect("login.aspx");
    }

  </script>

  <body>

    <h3><font face="宋体">使用 Cookie 身份验证</font></h3>

    <form runat=server>

      <h3><asp:label id="Welcome" runat=server/></h3>

      <asp:button text="注销" OnClick="Signout_Click" runat=server/>

    </form>

  </body>

</html>

-----------------------------
web.config

<configuration>
  <system.web>
      <authentication mode="Forms">
        <forms name=".ASPXUSERDEMO" loginUrl="login.aspx" protection="All" timeout="60" />
      </authentication>
      <authorization>
        <deny users="?" />
      </authorization>
    <globalization requestEncoding="UTF-8" responseEncoding="UTF-8" />
  </system.web>
</configuration>