2010-08-06 62 views
6

Có cách nào để liệt kê các vai trò nào có quyền truy cập vào một trang cụ thể qua mã không?Làm cách nào để lập danh sách ASP.Net Role có thể truy cập một trang?

Ví dụ, tôi có Testpage.aspx và tôi muốn liệt kê các vai trò được phép cho trang này khi người dùng truy cập trang. Trình quản lý URLAuthorizationManager phải có khả năng tìm ra điều này bằng cách nào đó, vì vậy phải có cách để biết vai trò nào được cấu hình trong webconfig cho một trang. hoặc URL.

Đây là webconfig giới hạn vai trò được phép xem trang này.

<location path="Testpage.aspx"> 
    <system.web> 
     <authorization> 
     <allow roles ="admin,sales" /> 
     </authorization> 
    </system.web> 
    </location> 

Nếu tôi có thể tìm thấy giải pháp, nó sẽ trả về "quản trị", "bán hàng". Bất kỳ ai biết làm thế nào tôi có thể làm điều này? Cảm ơn

+0

Ông có thể đánh dấu một trong những câu trả lời dưới đây là đúng? –

Trả lời

-1

Sử dụng Roles.GetAllRoles() phương pháp

http://msdn.microsoft.com/en-us/library/system.web.security.roles.getallroles.aspx

và đây là một ví dụ nơi họ liệt kê tất cả vai trò: http://weblogs.asp.net/scottgu/archive/2005/10/18/427754.aspx

+3

Điều này dường như liệt kê tất cả các vai trò có sẵn trong ứng dụng - không phải vai trò có thể truy cập trang –

+0

Bạn cũng có thể xem lớp ConfigurationLocation http://msdn.microsoft.com/en-us/library/3dab5d1z .aspx Lớp này được sử dụng nội bộ để bạn có thể muốn tiếp tục đào với Reflector. –

10

Bạn có thể sử dụng đoạn mã sau trong trang mà bạn muốn lấy thông tin.

var section = (AuthorizationSection) 
    WebConfigurationManager.GetSection("system.web/authorization"); 
var rules = section.Rules; 
var allowedRoles = rules 
    .OfType<AuthorizationRule>() 
    .Where(r => r.Action == AuthorizationRuleAction.Allow) 
    .Select(r => r.Roles).First(); 

Lý do gọi đến First() là cấu hình .NET là phân cấp. Giả sử bạn có hệ thống phân cấp trang web sau đây và cấu hình:

/Default.aspx 
/Web.config  (<allow roles="admin,user" />) 
/SubDir/ 
     /Test.aspx 
     /Web.config (<allow roles="admin,other" />) 

và bạn gọi mã trên từ Test.aspx.cs, sau đó tài sản AuthorizationSection.Rules chứa ba mục tương ứng với lần lượt các cấu hình từ /SubDir/Web.config, Web.configmachine.config. Vì vậy, phần tử đầu tiên chứa các vai trò adminother.

+0

Cảm ơn Ronald. Lời giải thích trong câu trả lời của bạn đã chỉ cho tôi đúng hướng và bây giờ tôi có thể liệt kê tất cả các vai trò cho một trang nhất định. – Chris

+1

Tốt để nghe điều đó. Nếu đây là một phần của câu trả lời cho câu hỏi của bạn, bạn có thể đánh dấu câu trả lời đó là câu trả lời không? Cảm ơn. –

+0

Chris, bạn nên đánh dấu câu trả lời này là "Đã trả lời" nếu nó giúp bạn giải quyết giải pháp. Nó cũng làm việc cho tôi. Cảm ơn Ronald. –

3

Vấn đề của tôi rất giống nhau, ngoại trừ tôi cần khả năng lặp qua tất cả các thư mục và thư mục con liên quan và hiển thị vai trò được phép cho từng trang web và thư mục thư mục. Tôi không thể sử dụng giải pháp của Ronald Wildenberg vì chúng tôi đang sử dụng .Net 2.0 nên chúng tôi không có chức năng LINQ.

Giải pháp của anh ấy đã cho tôi lộ trình tôi cần. Tôi cũng tìm thấy sự trợ giúp từ Đội hỗ trợ IIS của Microsoft, Managing Forms Authentication Programmatically. Tôi không muốn viết lại các tập tin cấu hình như chúng được đăng, thay vào đó chúng tôi cần khả năng hiển thị các vai trò được phép cho tất cả các thư mục và các trang trong ứng dụng của chúng tôi. Ứng dụng của chúng tôi là nhỏ. Nó có tổng cộng 15 thư mục và ít hơn 100 trang để điều này chạy khá nhanh chóng. Số dặm của bạn thay đổi tùy thuộc vào kích thước trang web của bạn.

Tôi bắt đầu từ thư mục gốc và tìm kiếm đệ quy tất cả các cấu hình web. Tôi đã thêm chúng với đường dẫn của chúng vào danh sách chuỗi sau đó được lặp qua danh sách và được gọi là hàm ListRoles của tôi. Chức năng này mở cấu hình web và nhận bộ sưu tập vị trí. Sau đó, nó tìm kiếm "system.web/ủy quyền" như Ronald đã làm. Nếu nó tìm thấy phần ủy quyền, nó sẽ lặp qua các quy tắc và loại trừ bất kỳ quy tắc thừa kế nào và tập trung vào AuthorizationRuleAction.Cho phép với vai trò liên quan:

using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.IO; 
using System.Web.Configuration; 

public void DisplayWebPageRoles() 
{ 
    //First walk the directories and find folders with Web.config files. 
    //Start at the root 
    DirectoryInfo baseDir = new DirectoryInfo(Server.MapPath("~/")); 

    //Do a little recursion to find Web.Configs search directory and subdirs 
    List<string> dirs = DirectoriesWithWebConfigFile(baseDir); 

    //Replace the folder path separator except for the baseDir  
    for (int i = 0; i < dirs.Count; i++) 
    { 
    dirs[i] = dirs[i].Replace(
      baseDir.FullName.Replace("\\", "/"), 
      "/" + baseDir.Name + (i > 0 ? "/" : "")); 
    } 

    //Now that we have the directories, we open the Web.configs we 
    //found and find allowed roles for locations and web pages. 
    for (int i = 0; i < dirs.Count; i++) 
    {    
    //Display on page, save to DB, etc... 
    ListRoles(dirs[i]); 
    } 
} 


public List<string> DirectoriesWithWebConfigFile(DirectoryInfo directory) 
{ 
    List<string> dirs = new List<string>(); 

    foreach (FileInfo file in directory.GetFiles("Web.config")) 
    { 
     dirs.Add(directory.FullName.Replace("\\","/"));    
    } 
    foreach (DirectoryInfo dir in directory.GetDirectories()) 
    { 
     dirs.AddRange(DirectoriesWithWebConfigFile(dir)); 
    } 
    return dirs; 
} 

private void ListRoles(string configFilePath) 
{   
    System.Configuration.Configuration configuration = 
    WebConfigurationManager.OpenWebConfiguration(configFilePath);    

    //Get location entries in web.config file 
    ConfigurationLocationCollection locCollection = configuration.Locations; 

    string locPath = string.Empty; 

    foreach (ConfigurationLocation loc in locCollection) 
    { 
     try 
     { 
      Configuration config = loc.OpenConfiguration(); 
      //Get the location path so we know if the allowed roles are 
      //assigned to a folder location or a web page. 
      locPath = loc.Path; 

      if (locPath.EndsWith(".js")) //Exclude Javascript libraries 
      { 
       continue; 
      } 
      AuthorizationSection authSection = 
       (AuthorizationSection)config 
           .GetSection("system.web/authorization"); 

      if (authSection != null) 
      { 
       foreach (AuthorizationRule ar in authSection.Rules) 
       { 
        if (IsRuleInherited(ar)) 
        { 
         continue; 
        } 

        if (ar.Action == AuthorizationRuleAction.Allow 
         && ar.Roles != null 
         && ar.Roles.Count > 0) 
        { 
         for (int x = 0; x < ar.Roles.Count; x++) 
         { 
          //Display on page, save to DB, etc... 
          //Testing 
          //Response.Write(
          // configFilePath + "/web.config" + "," 
          // + configFilePath + "/" + locPath + "," 
          // + ar.Roles[x] + "<br />"); 
         } 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      //Your Error Handling Code... 
     } 

    } 
} 

From French IIS support Team blog

private bool IsRuleInherited(AuthorizationRule rule) 
{ 
    //to see if an access rule is inherited from the web.config above 
    //the current one in the hierarchy, we look at two PropertyInformation 
    //objects - one corresponding to roles and one corresponding to 
    //users 

    PropertyInformation usersProperty = rule.ElementInformation.Properties["users"]; 
    PropertyInformation rolesProperty = rule.ElementInformation.Properties["roles"]; 

    //only one of these properties will be non null. If the property 
    //is equal to PropertyValueOrigin.Inherited, the this access rule 
    //if not returned in this web.config 
    if (usersProperty != null) 
    { 
     if (usersProperty.ValueOrigin == PropertyValueOrigin.Inherited) 
      return true; 
    } 

    if (rolesProperty != null) 
    { 
     if (rolesProperty.ValueOrigin == PropertyValueOrigin.Inherited) 
      return true; 
    } 

    return false; 
} 
+0

+1 cho câu trả lời khó chịu. – Teletha

Các vấn đề liên quan