ASP.NET Form验证随笔

王朝学院·作者佚名  2009-03-26  
宽屏版  字体: |||超大  

以前的项目遇到用户验证问题全都采用windows验证方式,最近公司项目中要求采用Forms验证方式。

总结如下:

1.登录页面代码

protected void Button1_Click(object sender, EventArgs e)

{

FormsAuthenticationTicket ticket=new FormsAuthenticationTicket (1,"LoginName",DateTime.Now,DateTime.Now.AddMinutes(20),false,"aaa",FormsAuthentication.FormsCookiePath);

HttpCookie cookie=new HttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket));

if(ticket.IsPersistent)

{

cookie.Expires = ticket.Expiration;

}

Response.Cookies.Add(cookie);

Response.Redirect("admin_page1.aspx");

}

2. Webconfig代码

<authentication mode="Forms" >

<forms name="authTest" loginUrl="~/admin/admin_login.aspx" timeout="20">

</forms>

</authentication>

</system.web>

<location path="admin">

<system.web>

<authorization>

<allow roles="admin,aaa"/>

<deny users="*"/>

</authorization>

</system.web>

</location>

3.Global文件代码

添加Application_AuthenticateRequest事件

if (HttpContext.Current.User != null)

{

if (HttpContext.Current.User.Identity.IsAuthenticated)

{

if (HttpContext.Current.User.Identity is FormsIdentity)

{

string userData;

string[] roles;

userData = string.Empty;

try

{

if (Request.Cookies["authTest"] != null)

{

FormsAuthenticationTicket ticket =

FormsAuthentication.Decrypt(Request.Cookies["authTest"].Value);

if (ticket != null)

{

userData = ticket.UserData;

}

}

}

catch (Exception E)

{

HttpContext.Current.Response.Write("<!-- " + E.Message + " -->");

}

roles = userData.Split(',');

HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, roles);

}

}

}

到此完成了Forms验证。

但我有疑问:如果客户端禁用了cookie那么forms验证是否就失效了呢?

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有