构建Forms验证(砖载)

构建基于forms的验证机制过程如下:
1,设置IIS为可匿名访问和asp.net web.config中设置为form验证
2,检索数据存储验证用户,并检索角色(如果不是基于角色可不用)
3,使用FormsAuthenticationTicket创建一个Cookie并回发到客户端,并存储
角色到票据中,如:
FormsAuthentication.SetAuthCookie(Username,true | false)
cookies保存时间:
HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires=DateTime.Now.AddDays(1)

如果需要存储角色,采用:
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(
1, // 版本号。
txtUserName.Text, // 与身份验证票关联的用户名。
DateTime.Now, // Cookie 的发出时间。
DateTime.Now.AddMinutes(20),// Cookie 的到期日期。
false, // 如果 Cookie 是持久的,为 true;否则为 false。
roles ); // 将存储在 Cookie 中的用户定义数据。
roles是一个角色字符串数组
string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密

存入Cookie
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);

Response.Cookies.Add(authCookie);

4,在Application_AuthenticateRequest事件中处理程序中(Global.asax)中,使用
票创建IPrincipal对象并存在HttpContext.User中
代码:
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密
string[] roles = authTicket.UserData.Split(new char[]{';'});//根据存入时的格式分解,;或|....
Context.User = new GenericPrincipal(Context.User.Identity, Roles);//存到HttpContext.User中

判断某个角色验证
HttpContext.Current.User.IsInRole(roles)
具体实现

Web.config文件
加入节点,name为COOKIE名称,loginUrl为没有通过验证跳转的地址
<system.web>
<authentication mode="Forms">
<forms name="Hstear"
loginUrl="login.aspx" protection="All" path="/" timeout="40"/>
</authentication>
</system.web>
设置目录访问 path为目录名,roles为票据中的角色名
发现网上的都说要单独一个WEB.CONFIG文件放在目录中,但实际在根目录中设置即可,单个文件也一样
<location path="Admin">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
Global.asax文件
Application_AuthenticateRequest事件中加入
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch(Exception ex)
{
return;
}
string[] roles = authTicket.UserData.Split(new char[]{','});//如果存取多个角色,我们把它分解
FormsIdentity id = new FormsIdentity( authTicket );
GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User =principal;//存到HttpContext.User中
}
来源:(http://blog.sina.com.cn/s/blog_4a9b5fcf0100c9bq.html) - FormsAuthenticationTicket基于forms的验证_先飞_新浪博客
原文地址:https://www.cnblogs.com/johnwonder/p/1756818.html