forms验证如此简单
1. 根目录下的web.config
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name=".ASPXAUTH"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<configuration>
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</configuration>
<configuration>
<system.web>
<authorization>
<allow users="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</configuration>
// 验证
if (theNode != null)
{
if (theNode.ChildNodes[1].InnerText == TextBox2.Text.Trim())
{
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text.Trim(), false);//简单一句
}
}
Response.Write("<script>alert('没有这个用户名或密码错误!')</script>");
1、 登录代码:
a、 书本上介绍的
private void Btn_Login_Click(object sender, System.EventArgs e)
{
if(this.Txt_UserName.Text=="Admin" && this.Txt_Password.Text=="123456")
{
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(this.Txt_UserName.Text,false);
}
}
b、 偶找了 N 久才找到的
private void Btn_Login_Click(object sender, System.EventArgs e)
{
if(this.Txt_UserName.Text=="Admin" && this.Txt_Password.Text=="123456")
{
System.Web.Security.FormsAuthentication.SetAuthCookie(this.Txt_UserName.Text,false);
Response.Redirect("Default.aspx");
}
}
以上两种都可发放验证后的Cookie,即通过验证,区别:
方法 a) 指验证后返回请求页面,俗称“从哪来就打哪去”。比如:用户没登录前直接在 IE 地址栏输入http://localhost/FormTest/UserInfo.aspx,那么该用户将看到的是Login.aspx?ReturnUrl=UserInfo.aspx,输入用户名与密码登录成功后,系统将根据“ReturnUrl”的值,返回相应的页面
方法 b) 则是分两步走:通过验证后就直接发放Cookie,跳转页面将由程序员自行指定,此方法多用于Default.aspx 使用框架结构的系统。
2、 退出代码:
private void Btn_LogOut_Click(object sender, System.EventArgs e)
{
System.Web.Security.FormsAuthentication.SignOut();
}
3. 检查是否通过验证
if(User.Identity.IsAuthenticated)
{
//你已通过验证,知道该怎么做了吧?
}
User.Identity还有两个属性AuthenticationType(验证类型)与Name(用户名称),大家要注意的是Name属性,此处的User.Identity.Name将得到,验证通过(RedirectFromLoginPage或SetAuthCookie)时,我们带入的第一个参数this.Txt_UserName.Text
private void Submit1_Click (object sender, System.EventArgs e)
{
if(this.TextBox_username.Text.Trim()== "HR_manager"
&& this.TextBox_password.Text.Trim() == "password")
{
// Success, create non-persistent authentication cookie.
FormsAuthentication.SetAuthCookie(
this.TextBox_username.Text.Trim(), flase);
FormsAuthenticationTicket ticket1 =
new FormsAuthenticationTicket(
1, // version
this.TextBox_username.Text.Trim(), // get username from the form
DateTime.Now, // issue time is now
DateTime.Now.AddMinutes(10), // expires in 10 minutes
false, // cookie is not persistent
"HR" // role assignment is stored
// in userData
);
HttpCookie cookie1 = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket1) );
Response.Cookies.Add(cookie1);
// 4. Do the redirect.
String returnUrl1;
// the login is successful
if (Request.QueryString["ReturnUrl"] == null)
{
returnUrl1 = "HRpages/HR_main.aspx";
}
//login not unsuccessful
else
{
returnUrl1 = Request.QueryString["ReturnUrl"];
}
Response.Redirect(returnUrl1);
}
}