【asp.net小札记】自定义文件夹访问权限

来源:互联网 发布:钱夫人淘宝店衣服批发 编辑:程序博客网 时间:2024/05/21 17:49

1、在用户登录时,添加以下函数:

private void WriteRoleToTicket(string username, string role) {        //建立身份验证票对象        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, role, "/");        //加密序列化验证票为字符串        string hashTicket = FormsAuthentication.Encrypt(ticket);        HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);        //生成Cookie        Response.Cookies.Add(userCookie);    }


2、在global.asax中,添加事件:

void Application_AuthenticateRequest(object sender,EventArgs e)    {        // Extract the forms authentication cookie        string cookieName = FormsAuthentication.FormsCookieName;        HttpCookie authCookie = Context.Request.Cookies[cookieName];        if (null == authCookie)        {            // There is no authentication cookie.            return;        }        FormsAuthenticationTicket authTicket = null;        try        {            authTicket = FormsAuthentication.Decrypt(authCookie.Value);        }        catch (Exception ex)        {            // Log exception details (omitted for simplicity)            return;        }        if (null == authTicket)        {            // Cookie failed to decrypt.            return;        }        // When the ticket was created, the UserData property was assigned a        // pipe delimited string of role names.        string[] roles = authTicket.UserData.Split(new char[] { '|' });        // Create an Identity object        FormsIdentity id = new FormsIdentity(authTicket);        // This principal will flow throughout the request.        System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, roles);        // Attach the new principal object to the current HttpContext object        Context.User = principal;    }


3、在需要访问控制的文件夹中,添加web.config,添加节点,类似于以下内容:

   <system.web>          <authorization>        <allow roles="专家"/>      </authorization>    </system.web>

0 0
原创粉丝点击