.net实现网站用户登录认证
cookie登录后同域名下的网站保持相同的登录状态。
登录
privatevoidSetAuthCookie(stringuserId,boolcreatePersistentCookie) { varticket=newFormsAuthenticationTicket(2,userId,DateTime.Now,DateTime.Now.AddDays(7),true,"",FormsAuthentication.FormsCookiePath); stringticketEncrypted=FormsAuthentication.Encrypt(ticket); HttpCookiecookie; if(createPersistentCookie)//是否在设置的过期时间内一直有效 { cookie=newHttpCookie(FormsAuthentication.FormsCookieName,ticketEncrypted) { HttpOnly=true, Path=FormsAuthentication.FormsCookiePath, Secure=FormsAuthentication.RequireSSL, Expires=ticket.Expiration, Domain="cnblogs.com"//这里设置认证的域名,同域名下包括子域名如aa.cnblogs.com或bb.cnblogs.com都保持相同的登录状态 }; } else { cookie=newHttpCookie(FormsAuthentication.FormsCookieName,ticketEncrypted) { HttpOnly=true, Path=FormsAuthentication.FormsCookiePath, Secure=FormsAuthentication.RequireSSL, //Expires=ticket.Expiration,//无过期时间的,浏览器关闭后失效 Domain="cnblogs.com" }; } HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); HttpContext.Current.Response.Cookies.Add(cookie); }
这样登录后,在同域名下的任何页面都可以得到用户状态
判断用户是否登录
publicboolIsAuthenticated { get { boolisPass=System.Web.HttpContext.Current.User.Identity.IsAuthenticated; if(!isPass) SignOut(); returnisPass; } }
得到当前的用户名
publicstringGetCurrentUserId() { return_httpContext.User.Identity.Name; }
下面给大家一个具体的实例
CS页代码:
usingSystem; usingSystem.Data; usingSystem.Configuration; usingSystem.Collections; usingSystem.Web; usingSystem.Web.Security; usingSystem.Web.UI; usingSystem.Web.UI.WebControls; usingSystem.Web.UI.WebControls.WebParts; usingSystem.Web.UI.HtmlControls; usingSystem.Data.SqlClient; publicpartialclassLogin:System.Web.UI.Page { protectedvoidPage_Load(objectsender,EventArgse) { } protectedvoidButton1_Click(objectsender,EventArgse) { stringconnString=Convert.ToString(ConfigurationManager.ConnectionStrings["001ConnectionString"]); //001ConnectionString是我在webconfig里配置的数据库连接。 SqlConnectionconn=newSqlConnection(connString); stringstrsql="select*fromUser_tablewhereUser_name='"+UserName.Text+"'andPassword='"+Password.Text+"'"; SqlCommandcmd=newSqlCommand(strsql,conn); conn.Open(); SqlDataReaderdr=cmd.ExecuteReader(CommandBehavior.CloseConnection); if(dr.Read()) { Response.Redirect("index.aspx"); conn.Close(); } else { FailureText.Text="登陆失败,请检查登陆信息!"; conn.Close(); Response.Write("<scriptlanguage=javascript>alert('登陆失败!.');</script>"); } } protectedvoidButton2_Click(objectsender,EventArgse)//文本框重置按钮 { UserName.Text=""; Password.Text=""; } }
下面是aspx页面代码:
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Login.aspx.cs"Inherits="Login"%> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server"> <title>无标题页</title> </head> <body> <formid="form1"runat="server"> <asp:PanelID="Panel1"runat="server"Height="101px"Width="231px"Wrap="False"> <table> <tr> <tdalign="center"colspan="2"> 用户登陆</td> </tr> <tr> <tdstyle="width:89px"> 用户名:</td> <tdstyle="width:100px"> <asp:TextBoxID="UserName"runat="server"Wrap="False"></asp:TextBox></td> </tr> <tr> <tdstyle="width:89px"> 密码:</td> <tdstyle="width:100px"> <asp:TextBoxID="Password"runat="server"TextMode="Password"Width="148px"Wrap="False"></asp:TextBox></td> </tr> <tr> <tdalign="center"colspan="2"style="text-align:center"> <asp:ButtonID="Button1"runat="server"Text="登陆"Width="50px"OnClick="Button1_Click"/> <asp:ButtonID="Button2"runat="server"Text="重置"Width="50px"OnClick="Button2_Click"/></td> </tr> <tr> <tdalign="center"colspan="2"> <asp:LabelID="FailureText"runat="server"Width="77px"></asp:Label></td> </tr> </table> </asp:Panel> </form> </body> </html>