asp.net登录验证FormsAuthenticationTicket和FormsAuthentication类
登录部分使用的类
FormsAuthentication 为 Web 应用程序管理 Forms 身份验证服务。
配置启用身份验证,WEB.config配置:
<system.web> <authentication mode="Forms"> <forms loginUrl="login.aspx" /> </authentication> <authorization> <deny users="?" /> </authorization> </system.web>
属性: FormsCookieName,用于存储 Forms 身份验证票证的 Cookie 名称。 默认值是“.ASPXAUTH”。
下面的代码示例设置FormsCookieName属性值,使用Web.config 文件中的name属性。
<authentication mode="Forms"> <forms loginUrl="member_login.aspx" cookieless="UseCookies" name=".ASPXFORMSAUTH" /> </authentication>
FormsCookieName使用 ASP.NET 应用程序配置文件name属性设置属性值。
FormsCookieName用于引用存储的 cookieFormsAuthenticationTicket信息。
FormsAuthenticationTicket 提供对票证的属性和值的访问,这些票证用于 Forms 身份验证对用户进行标识。
FormsAuthenticationTicket类用于创建一个对象,表示窗体身份验证用于标识身份验证的用户的身份验证票证。
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 = false; 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."; } }
验证部分
FormsIdentity和FormsAuthenticationTicket
string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = App.Context.Request.Cookies[cookieName]; if (null == authCookie) { // 沒有驗證 Cookie。 return; } if (authCookie.Value == null) { // 沒有驗證 Cookie。 return; } FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { // 記錄例外狀況詳細資料 (為簡單起見已省略) FileTxtLogs.WriteLog(ex.ToString()); return; } if (null == authTicket) { // Cookie 無法解密。 return; } // 建立 Identity 物件 FormsIdentity id = new FormsIdentity(authTicket); App.Context.User = new PermissionPrincipal(id);
IsAuthenticated 获取一个值,该值指示是否进行身份验证。
文章:How to: Implement Simple Forms Authentication
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2017-12-19 防止并发超扣库存
2017-12-19 快速排序