【asp.net小札記】自定義文件夾訪問權限

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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章