<system.web>2
<!-- 验证方式-->3
<authentication mode="Forms">4
<forms loginUrl="WebUI/Normal/Login.aspx"5
protection="All"6
timeout="30"7
name=".ASPXAUTH"8
path="/"9
requireSSL="false"10
slidingExpiration="true"11
defaultUrl="WebUI/Normal/MainPage.aspx"12
cookieless="UseDeviceProfile"13
enableCrossAppRedirects="false" />14
</authentication>15
</system.web><forms loginUrl="未通过验证时的登陆页面"
protection="All"
timeout="过期时间,分钟为单位"
name=".ASPXAUTH" 该配置意味着身份验证 Cookie 可通过未经 SSL 加密的信道进行传输。如果担心会话窃取,应考虑将 requireSSL 设置为 true
path="/"
requireSSL="false"
slidingExpiration="执行变化的会话生存期,用户在站点上处于活动状态,会话超时是否会定期重置。"
defaultUrl="应用程序的 Default.aspx 页"
cookieless="以指定应用程序对所有支持 Cookie 的浏览器都使用 Cookie。如果不支持 Cookie 的浏览器访问该站点,窗体身份验证在 URL 上打包身份验证票"
enableCrossAppRedirects="以指明窗体身份验证不支持自动处理在应用程序之间传递的查询字符串上的票证以及作为某个窗体 POST 的一部分传递的票证" />
</authentication>
然后在Global里处理Application_AuthenticateRequest事件
protected void Application_AuthenticateRequest(Object sender, EventArgs e)2
{3
HttpApplication app = (HttpApplication)sender;4
if (this.Request.IsAuthenticated)5
{6
if (HttpContext.Current.User != null)7
{8
FormsIdentity fi = (FormsIdentity)HttpContext.Current.User.Identity;//创建个FormsIdentity类,用他来访问当前用户的验证票9
//获得用户的验证票10
FormsAuthenticationTicket ticket = fi.Ticket;11
//从验证票中获得用户数据也就是角色数据12
string userData = ticket.UserData;13
//把用户数据用,分解成角色数组14
string[] roles = userData.Split(',');15
//重写当前用户信息,就是把角色信息也加入到用户信息中16
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(fi, roles);17
}18
}19
}
这个事件在每次请求的时候执行,所以尽量不要在里面执行复杂的操作,如果在里面进行以下判断
if (HttpContext.Current.User != null)//如果当前的http信息中存在用户信息
{
if (HttpContext.Current.User.Identity.IsAuthenticated)//如果当前用户的身份已经通过了验证
{
if (HttpContext.Current.User.Identity is FormsIdentity)//如果是窗体验证
有可能会造成图片不显示,具体原因不明
关于创建用户票证:
//partvalue为角色组 比如admin,member
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, id, DateTime.Now, DateTime.Now.AddMinutes(30), false, partvalue);
//把验证票加密
string hashTicket = FormsAuthentication.Encrypt(ticket);
//设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
//添加到COOKIE
Response.Cookies.Add(cookie);
角色过滤:
在响应权限的文件夹下创建配置文件
<system.web>
<authorization>
<allow roles="member"/>//允许的角色
<deny users="*"/>//过滤的用户
</authorization>
</system.web>

浙公网安备 33010602011771号