FormsAuthenticationTicket 类
提供對票證的屬性和值的訪問,這些票證用于 Forms 身份驗證對用戶進行標識。無法繼承此類。
命名空間:System.Web.Security
程序集:System.Web(在 system.web.dll 中)備注
FormsAuthenticationTicket 類用于創建表示身份驗證票證的對象,Forms 身份驗證使用這些票證來標識已經過身份驗證的用戶。Forms 身份驗證票證的屬性和值將轉換為加密字符串存儲在 Cookie 或 URL 中;這些加密字符串也會轉換回票證的屬性和值。
FormsAuthentication 類提供了 Encrypt 方法,用于從 FormsAuthenticationTicket 創建一個可存儲在 Cookie 或 URL 中的字符串值。FormsAuthentication 類還提供了一個 Decrypt 方法,用于從檢索自 Forms 身份驗證 Cookie 或 URL 的加密身份驗證票證創建一個 FormsAuthenticationTicket 對象。
可以使用 FormsIdentity 類的 Ticket 屬性訪問當前經過身份驗證的用戶的 FormsAuthenticationTicket。通過將當前 User 的 Identity 屬性強制轉換為類型 FormsIdentity,可以訪問當前 FormsIdentity 對象
下面的代碼示例使用 FormsCookieName 將 Encrypt 方法的結果存儲在 Cookie 中,并將用戶重定向到從 GetRedirectUrl 方法返回的 URL。
C#<%@ Page Language="C#" %> <%@ Import Namespace="System.Web.Security" %> <script runat="server"> private void Login_Click(Object sender, EventArgs e) { // Create a custom FormsAuthenticationTicket containing // application specific data for the user. string username = UserNameTextBox.Text; string password = UserPassTextBox.Text; bool isPersistent = PersistCheckBox.Checked; if (Membership.ValidateUser(username, password)) { string userData = "ApplicationSpecific data for this user."; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), isPersistent, userData, FormsAuthentication.FormsCookiePath); // Encrypt the ticket. string encTicket = FormsAuthentication.Encrypt(ticket); // Create the cookie. Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); // Redirect back to original URL. Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent)); } else { Msg.Text = "Login failed. Please check your user name and password and try again."; } } </script> <html> <head> <title>Forms Authentication Login</title> </head> <body> <form runat="server"> <span style="BACKGROUND: #80ff80"> <h3>Login Page</h3> </span> <asp:Label id="Msg" ForeColor="maroon" runat="server" /><P> <table border=0> <tbody> <tr> <td>Username:</td> <td><asp:TextBox id="UserNameTextBox" type="text" runat="server" /></td> <td> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="*" Display="Static" ControlToValidate="UserNameTextBox" /> </td> </tr> <tr> <td>Password:</td> <td><asp:TextBox id="UserPassTextBox" TextMode="Password" runat="server" /></td> <td> <asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="*" Display="Static" ControlToValidate="UserPassTextBox" /> </td> </tr> <tr> <td>Check here if this is <u>not</u><br>a public computer:</td> <td><asp:CheckBox id="PersistCheckBox" runat="server" autopostback="true" /></td> </tr> </tbody> </table> <input type="submit" value="Login" runat="server" onserverclick="Login_Click" /> </form> </body> </html>