:Forms , , 。
:
1、 , :
Admin ---->
Manager.aspx ---->
Users ---->
Welcome.aspx ---->
Error ---->
AccessError.htm ---->
default.aspx ---->
login.aspx ---->
web.config ---->
2、 web.config :
3、 login.aspx :
protected void btnLogin_Click(object sender, EventArgs e)
{
//Forms
FormsAuthentication.Initialize();
// ,txtName ,txtPassword
UserModel um = ValidUser(txtName.Text.Trim(),txtPassword.Text.Trim());
if (um != null)
{
//
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
um.Name,
DateTime.Now,
DateTime.Now.AddMinutes(30),
true,
um.Roles,//
FormsAuthentication.FormsCookiePath);
//
string hash = FormsAuthentication.Encrypt(ticket);
// cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
// cookie
Response.Cookies.Add(cookie);
//
Response.Redirect(FormsAuthentication.GetRedirectUrl(um.Name,false));
}
else
{
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "error_tip", "alert(' ! !');", true);
}
}
//
private UserModel ValidUser(string name, string password)
{
return new UserService().Validate(name, password);
}
4、 Global.asax, :
// User,
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null )
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
// HttpContext.Current.User,
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
5、 Admin Manager.aspx :
protected void Page_Load(object sender, EventArgs e)
{
//
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
// Admin
if (!id.Ticket.UserData.Contains("Admin"))
{
//
Response.Redirect("~/Error/AccessError.htm", true);
}
}
//
protected void btnExit_Click(object sender, EventArgs e)
{
//
FormsAuthentication.SignOut();
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert(' !');", true);
}
6、 Users Welcome.aspx :
protected void Page_Load(object sender, EventArgs e)
{
//
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
// User
if (!id.Ticket.UserData.Contains("User"))
{
//
Response.Redirect("~/Error/AccessError.htm", true);
}
}
//
protected void btnExit_Click(object sender, EventArgs e)
{
//
FormsAuthentication.SignOut();
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert(' !');", true);
}
:
:
3 , :
------------------------------------------
------------------------------------------
sa sa Admin,User
admin admin Admin
user user User
------------------------------------------
:
admin , Admin Manager.aspx ;
user , Users Welcome.aspx ;
sa , Admin Manager.aspx , Users Welcome.aspx 。
: , 。