web.config (只有用户信息存放在web.config中,才可以使用FormsAuthentication.Authenticate)
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
protection="All"
timeout="30"
name=".ASPXAUTH"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="Default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false">
<credentials passwordFormat="Clear">
<user name="xiaobai" password="xiaobai" />
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
login.aspx
<%@ Page Language="C#" Debug="true" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Forms Authentication Login</title>
</head>
<body>
<form id="LoginForm" runat="server">
<div style="background: #80ff80">
<h3>Login Page</h3>
</div>
<asp:Label id="Msg" ForeColor="Maroon" runat="server" />
<table border=0>
<tbody>
<tr>
<td>Username:</td>
<td><asp:TextBox ID="UserNameTextBox" 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>
login.aspx.cs
protected void Login_Click(object sender, EventArgs e)
{
string username = UserNameTextBox.Text;
string password = UserPassTextBox.Text;
bool isPersistent = PersistCheckBox.Checked;
if (FormsAuthentication.Authenticate(username, password))
{
FormsAuthentication.RedirectFromLoginPage(username, isPersistent);
/*
HttpCookie cookie = FormsAuthentication.GetAuthCookie(username, isPersistent);
cookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent);
*/
}
else
throw new Exception("登录失败!!!");
}
default.aspx.cs
protected void Logout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
数据库验证
protected void Login_Click(object sender, EventArgs e)
{
string username = UserNameTextBox.Text;
string password = UserPassTextBox.Text;
bool isPersistent = PersistCheckBox.Checked;
string source = "server=(local);integrated security=SSPI;database=mytest";
string select = "SELECT count(*) FROM [Login] WHERE UserName='" + username + "' AND UserPassword='" + password + "'";
// string update = "UPDATE [Login] set LoginTime=LoginTime+1, LastLogin='" + DateTime.Now + "' WHERE UserName='" + username + "'";
SqlConnection conn = new SqlConnection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select, conn);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count >= 1)
{
// cmd = new SqlCommand(update, conn);
// cmd.ExecuteNonQuery();
string userData = "ApplicationSpecific data for this user.";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(1), isPersistent, userData, FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// if (HttpContext.Current.User.IsInRole("Admin"))
// ......
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
// 不要使用FormsAuthentication.RedirectFromLoginPage,这个方法会重写cookie。
}
else
throw new Exception("登录失败!!!");
}
Login表
CREATE TABLE [Login] (
LoginId smallint IDENTITY(1,1) NOT NULL,
UserName nvarchar(20) NOT NULL,
UserPassword nvarchar(20) NOT NULL)
INSERT INTO [Login] VALUES ('xiaobai', 'xiaobai')
角色验证
<!--
设置目录角色访问权限
-->
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
protected void Login_Click(object sender, EventArgs e)
{
string username = UserNameTextBox.Text;
string password = UserPassTextBox.Text;
bool isPersistent = PersistCheckBox.Checked;
string source = "server=(local);integrated security=SSPI;database=mytest";
string select = "SELECT count(*) FROM [Login] WHERE UserName='" + username + "' AND UserPassword='" + password + "'";
SqlConnection conn = new SqlConnection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select, conn);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count >= 1)
{
string userData = "Admin";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(1), isPersistent, userData, FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
else
throw new Exception("登录失败!!!");
}
Global.asax
<%@ Import Namespace="System.Security.Principal" %>
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (null == authCookie)
return;
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[] { ',' });
// Context.User = new GenericPrincipal(new FormsIdentity(authTicket), roles);
Context.User = new GenericPrincipal(Context.User.Identity, roles);
}