2009-03-06 45 views
0

我正在執行一個自定義身份驗證方法,該方法使用輕型會話對象來保存用戶的授權詳細信息。現在我希望每個頁面(主要是主頁的子頁面)能夠分辨用戶是否應該訪問該頁面。在ASP.NET中使用子頁面的自定義授權

我應該創建一個頁面類並從那裏派生子頁面嗎?

應用程序知道哪些角色可以訪問哪個頁面的最佳方式是什麼?

回答

0

如果您在授權方面需要很大的靈活性,您最好使用自定義頁面類。否則,Web.config應該足夠了。

0

如果你使用自定義角色提供程序插入它,實際上你可以依賴於asp.net配置。有一種方法可以讓您檢查用戶是否有權訪問給定頁面:

System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal(
    "~/admin/test.aspx", principal, "GET" 
); 

然後,您可以在web.config上使用常規方法來配置授權。這樣做時,如果頁面位於同一文件夾中,則可以將web.config添加到該文件夾​​並適當配置授權。

0

在相同的情況下,我把需要的文件夾中的認證頁面,我定義在web.config中的位置元素來配置這樣的認證:

<location path="protected"> 
    <system.web> 
     <authorization> 
      <deny users="?"/> 
     </authorization> 
    </system.web> 
</location> 
1

我不喜歡的基本頁面的方法。對我來說,檢查安全措施已經太遲了。 您可以創建自己的HttpModule來檢查,將授權信息存儲在數據庫/ xml/...中或使用頁面上的反射來讀取它。

context.Handler將持有正在執行的類Page。因此,你可以做這樣的事情:

我複製我使用的代碼的一部分,它會檢查的作用,公共頁面,跳過對圖像和腳本(但你可以做得一樣好)檢查:

// In the HttpModule: 
    public void context_PreRequestHandlerExecute(object sender, EventArgs e) 
    { 
     HttpContext context = HttpContext.Current; 

     // Don´t validate permissions if the user wasn´t allowed by the asp.net security 
     // Neighter the advanced (custom) permissions are validated for non ASPX files. 
     if (!context.Request.FilePath.EndsWith(".aspx") || !context.User.Identity.IsAuthenticated) 
      return; 

     // Give full access to the unathorized error page, and logins, and so on... 
     string pageClass = context.Handler.GetType().BaseType.FullName; 

     string param = context.Request["p"]; 
     if (!string.IsNullOrEmpty(param)) 
      pageClass += "@" + param; 

     if (SecurityService.IsFullTrustClass(pageClass)) 
      return; 

     if (SecurityService.Context.CurrentPerson == null) 
     { 
      LogOff(); 
      return; 
     } 

     // Verify access permissions for the current page 
     IList<Role> roles = SecurityService.Context.CurrentPerson.Roles; 
     bool allow = SecurityService.HasAccessPermission(pageClass, roles); 

     if (!allow) 
     { 
      LogOff(); 
     } 
    }