借鉴别人的代码,自己整理下
有些代码不是很清楚,先记录一下
1.首先设置web.config
(1)把authentication的mode改为forms,原来默认的应该是windows,同时设置登录页面
<authentication mode="Forms">
<forms loginUrl="login.aspx" name=".ASPXAUTH"></forms> </authentication>(2)设置权限目录
location这个目录和system.web是同一级目录,path为设置权限的目录,即为指定该目录下文件的访问权限
<location path="User">
<system.web> <authorization> <allow roles="user"/> <deny users="*"/> </authorization> </system.web> </location>(可以设置多个location,这样可以设置多个文件夹下目录的权限)
2 .登录页面设置
(1)验证方法
/// <summary>
/// Set information for authentication /// </summary> /// <param name="username">Username</param> /// <param name="roles">Roles</param> private void SetAuthentication(string username, string roles) { // Create a new ticket used for authentication FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version username, // Username associated with ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(60), // Date/time to expire false, // "true" for a persistent user cookie roles, // User-data, in this case the roles FormsAuthentication.FormsCookiePath);// Path cookie valid for// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, // Name of auth cookie hash); // Hashed ticket// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;// Add the cookie to the list for outgoing response
HttpContext.Current.Response.Cookies.Add(cookie); }(2)登录
if(验证成功)
{
SetAuthentication(uname, "user");//第一个为名字,第二个为角色
}
3.Global.asax设置
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;// Get the stored user-data, in this case, our roles
string userData = ticket.UserData; string[] roles = userData.Split(','); HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles); } } } }经测试可以使用,设置权限的文件夹下必须为允许的角色能够打开,起到了分文件夹权限的作用
暂时不知道优缺点。