62,073
社区成员
发帖
与我相关
我的任务
分享
<authentication mode="Forms">
<form name=".ASPXFORMSDEMO" loginUrl="logon.aspx" protection="All" path="/" timeout="30"/>
</authentication>
<authentication>
<deny users="?"/>
<allow users="*"/>
</authentication>
if exists (select * from sysobjects where id =
object_id(N'[dbo].[Users]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Users]
GO
CREATE TABLE [dbo].[Users] (
[uname] [varchar] (15) NOT NULL ,
[Pwd] [varchar] (25) NOT NULL ,
[userRole] [varchar] (25) NOT NULL ,
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] WITH NOCHECK ADD
CONSTRAINT [PK_Users] PRIMARY KEY NONCLUSTERED
(
[uname]
) ON [PRIMARY]
GO
INSERT INTO Users values('user1','user1','Manager')
INSERT INTO Users values('user2','user2','Admin')
INSERT INTO Users values('user3','user3','User')
GO
<h3>
<font face="Verdana">Logon Page </font>
</h3>
<table>
<tr>
<td>Email: </td>
<td> <input id="txtUserName" type="text" runat="server"> </td>
<td> <ASP:RequiredFieldValidator ControlToValidate="txtUserName"
Display="Static" ErrorMessage="*" runat="server"
ID="vUserName" /> </td>
</tr>
<tr>
<td>Password: </td>
<td> <input id="txtUserPass" type="password" runat="server"> </td>
<td> <ASP:RequiredFieldValidator ControlToValidate="txtUserPass"
Display="Static" ErrorMessage="*" runat="server"
ID="vUserPass" />
</td>
</tr>
<tr>
<td>Persistent Cookie: </td>
<td> <ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" /> </td>
<td> </td>
</tr>
</table>
<input type="submit" Value="Logon" runat="server" ID="cmdLogin"> <p> </p>
<asp:Label id="lblMsg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" />
using System.Data.SqlClient;
using System.Web.Security;
private bool ValidateUser( string userName, string passWord )
{
SqlConnection conn;
SqlCommand cmd;
string lookupPassword = null;
// Check for invalid userName.
// userName must not be null and must be between 1 and 15 characters.
if ( ( null == userName ) ¦ ¦ ( 0 == userName.Length ) ¦ ¦ ( userName.Length > 15 ) )
{
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of userName failed." );
return false;
}
// Check for invalid passWord.
// passWord must not be null and must be between 1 and 25 characters.
if ( ( null == passWord ) ¦ ¦ ( 0 == passWord.Length ) ¦ ¦ ( passWord.Length > 25 ) )
{
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of passWord failed." );
return false;
}
try
{
// Consult with your SQL Server administrator for an appropriate connection
// string to use to connect to your local SQL Server.
conn = new SqlConnection( "server=localhost;Integrated Security=SSPI;database=pubs" );
conn.Open();
// Create SqlCommand to select pwd field from users table given supplied userName.
cmd = new SqlCommand( "Select pwd from users where uname=@userName", conn );
cmd.Parameters.Add( "@userName", SqlDbType.VarChar, 25 );
cmd.Parameters["@userName"].Value = userName;
// Execute command and fetch pwd field into lookupPassword string.
lookupPassword = (string) cmd.ExecuteScalar();
// Cleanup command and connection objects.
cmd.Dispose();
conn.Dispose();
}
catch ( Exception ex )
{
// Add error handling here for debugging.
// This error message should not be sent back to the caller.
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Exception " + ex.Message );
}
// If no password found, return false.
if ( null == lookupPassword )
{
// You could write failed login attempts here to event log for additional security.
return false;
}
// Compare lookupPassword and input passWord, using a case-sensitive comparison.
return ( 0 == string.Compare( lookupPassword, passWord, false ) );
}
(注:这段代码的意思是先判断输入的用户名和密码是否符合一定的条件,如上,如果符合则连接到数据库,并且根据用户名来取出密码并返回密码,最后再判断取出的密码是否为空,如果不为空则再判断取出的密码和输入的密码是否相同,最后的false参数为不区分大小写) private void cmdLogin_ServerClick(object sender,System.EventArgs e)
{
if(ValidateUser(txtUserName.value,txtUserPass.Value))
FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,chkPresistCookie.Checked);
else
Response.Redirect("logon.aspx",true);
}
private void cmdLogin_ServerClick(object sender,System.EventArgs e)
{
if(ValidateUser(txtUserName.value,txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt=new FormsAuthenticationTicket(1,txtUserName.value,DateTime.Now,DateTime.Now.AddMinutes(30),chkPersistCookie.Checked,"your custom data"); //创建一个验证票据
cookiestr=FormsAuthentication.Encrypt(tkt);//并且加密票据
ck=new HttpCookie(FormsAuthentication.FormsCookieName,cookiestr);// 创建cookie
if(chkpersistCookie.Checked) //如果用户选择了保存密码
ck.Expires=tkt.Expiratioin;//设置cookie有效期
ck.Path=FormsAuthentication.FormsCookiePath;//cookie存放路径
Response.Cookies.Add(ck);
string strRedirect;
strRedirect=Request["ReturnUrl"];
if(strRedirect==null)
strRedirect="default.aspx";
Response.Redirect(strRedirect,true);
}
else
Reponse.Redirect("logon.aspx",true);
}
this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick);
<input type="submit" Value="SignOut" runat="server" id="cmdSignOut">
这个按钮用来注销表单验证会话。 using System.Web.Security;
private void cmdSignOut_ServerClick(object sender,System.EventArgs e)
{
FormsAuthentication.SignOut();//注销
Response.Redirect("logon.aspx",true);
}
this.cmdSignOut.ServerClick += new System.EventHandler(this.cmdSignOut_ServerClick);