现在的位置: 首页 > 综合 > 正文

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

2012年02月19日 ⁄ 综合 ⁄ 共 2285字 ⁄ 字号 评论关闭

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>

抱歉!评论已关闭.