2009-04-07 16 views
53

के साथ .NET में उपयोगकर्ता समूह और भूमिका प्रबंधन मैं वर्तमान में .NET आधारित परियोजनाओं के लिए उपयोगकर्ता भूमिकाओं और अनुमतियों को संग्रहीत करने के तरीकों का शोध कर रहा हूं। इनमें से कुछ परियोजनाएं वेब आधारित हैं, कुछ नहीं हैं। मैं वर्तमान में प्रोजेक्ट प्रकारों में एक सतत, पोर्टेबल तरीके से जो खोज रहा हूं उसे हासिल करने के लिए सबसे अच्छी विधि खोजने के लिए संघर्ष कर रहा हूं।सक्रिय निर्देशिका

जहां मैं हूं, हम मूल उपयोगकर्ता जानकारी के लिए संपर्क के हमारे एकल बिंदु के रूप में सक्रिय निर्देशिका का लाभ उठाने की तलाश में हैं। इस वजह से, हम प्रत्येक एप्लिकेशन के उपयोगकर्ताओं के लिए एक कस्टम डेटाबेस बनाए रखने की आवश्यकता नहीं रखते हैं क्योंकि वे पहले ही सक्रिय निर्देशिका में संग्रहीत हैं और सक्रिय रूप से वहां बनाए रखा गया है। इसके अतिरिक्त, यदि संभव हो तो हम अपना खुद का सुरक्षा मॉडल/कोड लिखना नहीं चाहते हैं और माइक्रोसॉफ्ट द्वारा प्रदान किए गए सुरक्षा अनुप्रयोग ब्लॉक की तरह कुछ पूर्व-मौजूदा उपयोग करना चाहते हैं।

कुछ परियोजनाओं को केवल मूल विशेषाधिकारों की आवश्यकता होती है, जैसे पढ़ना, लिखना या कोई पहुंच नहीं। अन्य परियोजनाओं को अधिक जटिल अनुमतियों की आवश्यकता होती है। उन अनुप्रयोगों के उपयोगकर्ताओं को कुछ क्षेत्रों तक पहुंच प्रदान की जा सकती है, लेकिन दूसरों को नहीं, और प्रत्येक क्षेत्र में उनकी अनुमतियां बदल सकती हैं। ऐप का एक प्रशासन अनुभाग इस एक्सेस को नियंत्रित और परिभाषित करेगा, एडी टूल्स नहीं।

वर्तमान में, हम अपने इंट्रानेट पर प्रमाणीकरण करने के लिए एकीकृत विंडोज प्रमाणीकरण का उपयोग कर रहे हैं। यह मूल उपयोगकर्ता जानकारी खोजने के लिए अच्छी तरह से काम करता है, और मैंने देखा है कि एक सक्रिय निर्देशिका भूमिका प्रदाता प्रदान करने के लिए ASP.NET को बढ़ाया जा सकता है, इसलिए मैं किसी भी सुरक्षा समूह को उपयोगकर्ता से संबंधित कर सकता हूं। लेकिन, मुझे इस विधि के पतन की तरह लगता है कि सबकुछ सक्रिय निर्देशिका में संग्रहीत है, जो चीजों को बहुत बड़ा होने पर बनाए रखने के लिए गड़बड़ी कर सकता है।

इस एक ही पंक्ति साथ, मैं भी सक्रिय निर्देशिका लाइटवेट डायरेक्टरी सेवा है, जो लगता है कि यह हमारे स्कीमा का विस्तार करने और केवल आवेदन विशिष्ट विशेषताओं और समूहों जोड़ सकता है लगता है के बारे में सुना। समस्या यह है कि मुझे यह नहीं पता कि यह कैसे किया जाएगा या यह कैसे काम करता है। एमएसडीएन लेख हैं जो वर्णन करते हैं कि इस उदाहरण से कैसे बात करें और नया उदाहरण कैसे बनाएं, लेकिन मेरे प्रश्न का उत्तर देने के लिए कुछ भी नहीं लगता है।

मेरा प्रश्न है: आपके अनुभव के आधार पर, क्या मैं सही रास्ते पर जा रहा हूं? क्या मैं केवल सक्रिय निर्देशिका का उपयोग कर संभव करना चाहता हूं, या अन्य टूल्स का उपयोग करना है?


अन्य तरीकों मैं देखा है:

  • कई web.config फ़ाइलें [stackoverflow]
  • एक कस्टम सुरक्षा मॉडल और डेटाबेस बनाना का उपयोग अनुप्रयोगों भर में उपयोगकर्ताओं को प्रबंधित करने
+0

मैंने नमूना कोड जोड़ा है, जैसा अनुरोध किया गया है –

उत्तर

97

आपके प्रमाणीकरण के लिए एडी का उपयोग करना एक अच्छा विचार है, क्योंकि आपको वैसे भी सभी को जोड़ने की जरूरत है, और इंट्रा के लिए शुद्ध उपयोगकर्ताओं को अतिरिक्त लॉगिन की आवश्यकता नहीं है।

आप सही हैं कि एएसपी.नेट आपको एक प्रदाता का उपयोग करने की अनुमति देता है जो आपको एडी के खिलाफ प्रमाणित करने की अनुमति देगा, हालांकि समूह सदस्यता समर्थन देने के लिए कुछ भी शामिल नहीं है (हालांकि यदि आप चाहते हैं तो इसे कार्यान्वित करने में काफी छोटा है। एक नमूना प्रदान कर सकते हैं)।

असली मुद्दा यह है कि यदि आप प्रत्येक ऐप के भीतर अनुमतियों को परिभाषित करने के लिए एडी समूह का उपयोग करना चाहते हैं, तो हाँ?

यदि ऐसा है तो आप ASP.NET कि भी ApplicationServices के माध्यम से WinForms और WPF ऐप्स द्वारा उपयोग किया जा सकता है के लिए अपने स्वयं के RoleProvider बनाने का विकल्प होता है।यह रोलप्रोवाइडर एडी में उपयोगकर्ता की आईडी को प्रति ऐप समूहों/भूमिकाओं से जोड़ सकता है, जिसे आप अपने स्वयं के कस्टम डेटाबेस में स्टोर कर सकते हैं, जो प्रत्येक ऐप को इन भूमिकाओं के प्रशासन को एडी में अतिरिक्त विशेषाधिकारों की आवश्यकता के बिना अनुमति देता है।

यदि आप चाहते हैं कि आप एडी समूहों के साथ ओवरराइड और ऐप भूमिकाएं भी जोड़ सकें, तो यदि वे एडी में कुछ वैश्विक "एडमिन" समूह में हैं तो उन्हें ऐप भूमिका सदस्यता के बावजूद ऐप में पूर्ण अनुमति मिलती है। इसके विपरीत यदि उनके पास एडी में कोई समूह या संपत्ति है, तो कहने के लिए कि उन्हें निकाल दिया गया है, आप सभी ऐप भूमिका सदस्यता को अनदेखा कर सकते हैं और सभी पहुंच प्रतिबंधित कर सकते हैं (क्योंकि एचआर शायद उन्हें प्रत्येक ऐप से नहीं हटाएगा, मानते हैं कि उन्हें उनके बारे में भी पता है सब!)।

नोट::

नमूना कोड का अनुरोध किया के रूप में जोड़ा इस मूल काम http://www.codeproject.com/Articles/28546/Active-Directory-Roles-Provider

अपने ActiveDirectoryMembershipProvider के लिए आप केवल ValidateUser विधि लागू करने की आवश्यकता के आधार पर, यदि आप वांछित यद्यपि आप अधिक लागू कर सकता है, नई AccountManagement नाम स्थान इस तुच्छ बनाता है:

// assumes: using System.DirectoryServices.AccountManagement; 
public override bool ValidateUser(string username, string password) 
{ 
    bool result = false; 

    try 
    { 
    using(var context = 
     new PrincipalContext(ContextType.Domain, "yourDomainName")) 
    { 
     result = context.ValidateCredentials(username, password); 
    } 
    } 
    catch(Exception ex) 
    { 
    // TODO: log exception 
    } 

    return result; 
} 

अपनी भूमिका प्रदाता के लिए यह थोड़ा और अधिक काम है, और भी है Google जैसे खोजशब्दों को खोजते समय कुछ महत्वपूर्ण मुद्दों को खोजना चाहते हैं, जिन्हें आप बहिष्कृत करना चाहते हैं।

शायद यह एक पूर्ण ब्लॉग पोस्ट के लायक है, लेकिन इससे आपको शुरुआत करने में मदद मिलनी चाहिए, यह सत्र चर में कैशिंग लुकअप है, एक नमूना के रूप में कि आप प्रदर्शन में सुधार कैसे कर सकते हैं (क्योंकि एक पूर्ण कैश नमूना बहुत लंबा होगा)।

using System; 
using System.Collections.Generic; 
using System.Collections.Specialized; 
using System.Configuration.Provider; 
using System.Diagnostics; 
using System.DirectoryServices; 
using System.DirectoryServices.AccountManagement; 
using System.Linq; 
using System.Web; 
using System.Web.Hosting; 
using System.Web.Security; 

namespace MyApp.Security 
{ 
    public sealed class ActiveDirectoryRoleProvider : RoleProvider 
    { 
     private const string AD_FILTER = "(&(objectCategory=group)(|(groupType=-2147483646)(groupType=-2147483644)(groupType=-2147483640)))"; 
     private const string AD_FIELD = "samAccountName"; 

     private string _activeDirectoryConnectionString; 
     private string _domain; 

     // Retrieve Group Mode 
     // "Additive" indicates that only the groups specified in groupsToUse will be used 
     // "Subtractive" indicates that all Active Directory groups will be used except those specified in groupsToIgnore 
     // "Additive" is somewhat more secure, but requires more maintenance when groups change 
     private bool _isAdditiveGroupMode; 

     private List<string> _groupsToUse; 
     private List<string> _groupsToIgnore; 
     private List<string> _usersToIgnore; 

     #region Ignore Lists 

     // IMPORTANT - DEFAULT LIST OF ACTIVE DIRECTORY USERS TO "IGNORE" 
     //    DO NOT REMOVE ANY OF THESE UNLESS YOU FULLY UNDERSTAND THE SECURITY IMPLICATIONS 
     //    VERYIFY THAT ALL CRITICAL USERS ARE IGNORED DURING TESTING 
     private String[] _DefaultUsersToIgnore = new String[] 
     { 
      "Administrator", "TsInternetUser", "Guest", "krbtgt", "Replicate", "SERVICE", "SMSService" 
     }; 

     // IMPORTANT - DEFAULT LIST OF ACTIVE DIRECTORY DOMAIN GROUPS TO "IGNORE" 
     //    PREVENTS ENUMERATION OF CRITICAL DOMAIN GROUP MEMBERSHIP 
     //    DO NOT REMOVE ANY OF THESE UNLESS YOU FULLY UNDERSTAND THE SECURITY IMPLICATIONS 
     //    VERIFY THAT ALL CRITICAL GROUPS ARE IGNORED DURING TESTING BY CALLING GetAllRoles MANUALLY 
     private String[] _defaultGroupsToIgnore = new String[] 
      { 
       "Domain Guests", "Domain Computers", "Group Policy Creator Owners", "Guests", "Users", 
       "Domain Users", "Pre-Windows 2000 Compatible Access", "Exchange Domain Servers", "Schema Admins", 
       "Enterprise Admins", "Domain Admins", "Cert Publishers", "Backup Operators", "Account Operators", 
       "Server Operators", "Print Operators", "Replicator", "Domain Controllers", "WINS Users", 
       "DnsAdmins", "DnsUpdateProxy", "DHCP Users", "DHCP Administrators", "Exchange Services", 
       "Exchange Enterprise Servers", "Remote Desktop Users", "Network Configuration Operators", 
       "Incoming Forest Trust Builders", "Performance Monitor Users", "Performance Log Users", 
       "Windows Authorization Access Group", "Terminal Server License Servers", "Distributed COM Users", 
       "Administrators", "Everybody", "RAS and IAS Servers", "MTS Trusted Impersonators", 
       "MTS Impersonators", "Everyone", "LOCAL", "Authenticated Users" 
      }; 
     #endregion 

     /// <summary> 
     /// Initializes a new instance of the ADRoleProvider class. 
     /// </summary> 
     public ActiveDirectoryRoleProvider() 
     { 
      _groupsToUse = new List<string>(); 
      _groupsToIgnore = new List<string>(); 
      _usersToIgnore = new List<string>(); 
     } 

     public override String ApplicationName { get; set; } 

     /// <summary> 
     /// Initialize ADRoleProvider with config values 
     /// </summary> 
     /// <param name="name"></param> 
     /// <param name="config"></param> 
     public override void Initialize(String name, NameValueCollection config) 
     { 
      if (config == null) 
       throw new ArgumentNullException("config"); 

      if (String.IsNullOrEmpty(name)) 
       name = "ADRoleProvider"; 

      if (String.IsNullOrEmpty(config[ "description" ])) 
      { 
       config.Remove("description"); 
       config.Add("description", "Active Directory Role Provider"); 
      } 

      // Initialize the abstract base class. 
      base.Initialize(name, config); 

      _domain = ReadConfig(config, "domain"); 
      _isAdditiveGroupMode = (ReadConfig(config, "groupMode") == "Additive"); 
      _activeDirectoryConnectionString = ReadConfig(config, "connectionString"); 

      DetermineApplicationName(config); 
      PopulateLists(config); 
     } 

     private string ReadConfig(NameValueCollection config, string key) 
     { 
      if (config.AllKeys.Any(k => k == key)) 
       return config[ key ]; 

      throw new ProviderException("Configuration value required for key: " + key); 
     } 

     private void DetermineApplicationName(NameValueCollection config) 
     { 
      // Retrieve Application Name 
      ApplicationName = config[ "applicationName" ]; 
      if (String.IsNullOrEmpty(ApplicationName)) 
      { 
       try 
       { 
        string app = 
         HostingEnvironment.ApplicationVirtualPath ?? 
         Process.GetCurrentProcess().MainModule.ModuleName.Split('.').FirstOrDefault(); 

        ApplicationName = app != "" ? app : "/"; 
       } 
       catch 
       { 
        ApplicationName = "/"; 
       } 
      } 

      if (ApplicationName.Length > 256) 
       throw new ProviderException("The application name is too long."); 
     } 

     private void PopulateLists(NameValueCollection config) 
     { 
      // If Additive group mode, populate GroupsToUse with specified AD groups 
      if (_isAdditiveGroupMode && !String.IsNullOrEmpty(config[ "groupsToUse" ])) 
       _groupsToUse.AddRange(
        config[ "groupsToUse" ].Split(',').Select(group => group.Trim()) 
       ); 

      // Populate GroupsToIgnore List<string> with AD groups that should be ignored for roles purposes 
      _groupsToIgnore.AddRange(
       _defaultGroupsToIgnore.Select(group => group.Trim()) 
      ); 

      _groupsToIgnore.AddRange(
       (config[ "groupsToIgnore" ] ?? "").Split(',').Select(group => group.Trim()) 
      ); 

      // Populate UsersToIgnore ArrayList with AD users that should be ignored for roles purposes 
      string usersToIgnore = config[ "usersToIgnore" ] ?? ""; 
      _usersToIgnore.AddRange(
       _DefaultUsersToIgnore 
        .Select(value => value.Trim()) 
        .Union(
         usersToIgnore 
          .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) 
          .Select(value => value.Trim()) 
        ) 
      ); 
     } 

     private void RecurseGroup(PrincipalContext context, string group, List<string> groups) 
     { 
      var principal = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, group); 

      if (principal == null) 
       return; 

      List<string> res = 
       principal 
        .GetGroups() 
        .ToList() 
        .Select(grp => grp.Name) 
        .ToList(); 

      groups.AddRange(res.Except(groups)); 
      foreach (var item in res) 
       RecurseGroup(context, item, groups); 
     } 

     /// <summary> 
     /// Retrieve listing of all roles to which a specified user belongs. 
     /// </summary> 
     /// <param name="username"></param> 
     /// <returns>String array of roles</returns> 
     public override string[] GetRolesForUser(string username) 
     { 
      string sessionKey = "groupsForUser:" + username; 

      if (HttpContext.Current != null && 
       HttpContext.Current.Session != null && 
       HttpContext.Current.Session[ sessionKey ] != null 
      ) 
       return ((List<string>) (HttpContext.Current.Session[ sessionKey ])).ToArray(); 

      using (PrincipalContext context = new PrincipalContext(ContextType.Domain, _domain)) 
      { 
       try 
       { 
        // add the users groups to the result 
        var groupList = 
         UserPrincipal 
          .FindByIdentity(context, IdentityType.SamAccountName, username) 
          .GetGroups() 
          .Select(group => group.Name) 
          .ToList(); 

        // add each groups sub groups into the groupList 
        foreach (var group in new List<string>(groupList)) 
         RecurseGroup(context, group, groupList); 

        groupList = groupList.Except(_groupsToIgnore).ToList(); 

        if (_isAdditiveGroupMode) 
         groupList = groupList.Join(_groupsToUse, r => r, g => g, (r, g) => r).ToList(); 

        if (HttpContext.Current != null) 
         HttpContext.Current.Session[ sessionKey ] = groupList; 

        return groupList.ToArray(); 
       } 
       catch (Exception ex) 
       { 
        // TODO: LogError("Unable to query Active Directory.", ex); 
        return new[] { "" }; 
       } 
      } 
     } 

     /// <summary> 
     /// Retrieve listing of all users in a specified role. 
     /// </summary> 
     /// <param name="rolename">String array of users</param> 
     /// <returns></returns> 
     public override string[] GetUsersInRole(String rolename) 
     { 
      if (!RoleExists(rolename)) 
       throw new ProviderException(String.Format("The role '{0}' was not found.", rolename)); 

      using (PrincipalContext context = new PrincipalContext(ContextType.Domain, _domain)) 
      { 
       try 
       { 
        GroupPrincipal p = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, rolename); 

        return (

         from user in p.GetMembers(true) 
         where !_usersToIgnore.Contains(user.SamAccountName) 
         select user.SamAccountName 

        ).ToArray(); 
       } 
       catch (Exception ex) 
       { 
        // TODO: LogError("Unable to query Active Directory.", ex); 
        return new[] { "" }; 
       } 
      } 
     } 

     /// <summary> 
     /// Determine if a specified user is in a specified role. 
     /// </summary> 
     /// <param name="username"></param> 
     /// <param name="rolename"></param> 
     /// <returns>Boolean indicating membership</returns> 
     public override bool IsUserInRole(string username, string rolename) 
     { 
      return GetUsersInRole(rolename).Any(user => user == username); 
     } 

     /// <summary> 
     /// Retrieve listing of all roles. 
     /// </summary> 
     /// <returns>String array of roles</returns> 
     public override string[] GetAllRoles() 
     { 
      string[] roles = ADSearch(_activeDirectoryConnectionString, AD_FILTER, AD_FIELD); 

      return (

       from role in roles.Except(_groupsToIgnore) 
       where !_isAdditiveGroupMode || _groupsToUse.Contains(role) 
       select role 

      ).ToArray(); 
     } 

     /// <summary> 
     /// Determine if given role exists 
     /// </summary> 
     /// <param name="rolename">Role to check</param> 
     /// <returns>Boolean indicating existence of role</returns> 
     public override bool RoleExists(string rolename) 
     { 
      return GetAllRoles().Any(role => role == rolename); 
     } 

     /// <summary> 
     /// Return sorted list of usernames like usernameToMatch in rolename 
     /// </summary> 
     /// <param name="rolename">Role to check</param> 
     /// <param name="usernameToMatch">Partial username to check</param> 
     /// <returns></returns> 
     public override string[] FindUsersInRole(string rolename, string usernameToMatch) 
     { 
      if (!RoleExists(rolename)) 
       throw new ProviderException(String.Format("The role '{0}' was not found.", rolename)); 

      return (
       from user in GetUsersInRole(rolename) 
       where user.ToLower().Contains(usernameToMatch.ToLower()) 
       select user 

      ).ToArray(); 
     } 

     #region Non Supported Base Class Functions 

     /// <summary> 
     /// AddUsersToRoles not supported. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory. 
     /// </summary> 
     public override void AddUsersToRoles(string[] usernames, string[] rolenames) 
     { 
      throw new NotSupportedException("Unable to add users to roles. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory."); 
     } 

     /// <summary> 
     /// CreateRole not supported. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory. 
     /// </summary> 
     public override void CreateRole(string rolename) 
     { 
      throw new NotSupportedException("Unable to create new role. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory."); 
     } 

     /// <summary> 
     /// DeleteRole not supported. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory. 
     /// </summary> 
     public override bool DeleteRole(string rolename, bool throwOnPopulatedRole) 
     { 
      throw new NotSupportedException("Unable to delete role. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory."); 
     } 

     /// <summary> 
     /// RemoveUsersFromRoles not supported. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory. 
     /// </summary> 
     public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames) 
     { 
      throw new NotSupportedException("Unable to remove users from roles. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory."); 
     } 
     #endregion 

     /// <summary> 
     /// Performs an extremely constrained query against Active Directory. Requests only a single value from 
     /// AD based upon the filtering parameter to minimize performance hit from large queries. 
     /// </summary> 
     /// <param name="ConnectionString">Active Directory Connection String</param> 
     /// <param name="filter">LDAP format search filter</param> 
     /// <param name="field">AD field to return</param> 
     /// <returns>String array containing values specified by 'field' parameter</returns> 
     private String[] ADSearch(String ConnectionString, String filter, String field) 
     { 
      DirectorySearcher searcher = new DirectorySearcher 
      { 
       SearchRoot = new DirectoryEntry(ConnectionString), 
       Filter = filter, 
       PageSize = 500 
      }; 
      searcher.PropertiesToLoad.Clear(); 
      searcher.PropertiesToLoad.Add(field); 

      try 
      { 
       using (SearchResultCollection results = searcher.FindAll()) 
       { 
        List<string> r = new List<string>(); 
        foreach (SearchResult searchResult in results) 
        { 
         var prop = searchResult.Properties[ field ]; 
         for (int index = 0; index < prop.Count; index++) 
          r.Add(prop[ index ].ToString()); 
        } 

        return r.Count > 0 ? r.ToArray() : new string[ 0 ]; 
       } 
      } 
      catch (Exception ex) 
      { 
       throw new ProviderException("Unable to query Active Directory.", ex); 
      } 
     } 
    } 
} 

एक नमूना config इस के लिए उप-धारा प्रविष्टि के रूप में निम्नानुसार होगा:

<roleManager enabled="true" defaultProvider="ActiveDirectory"> 
    <providers> 
    <clear/> 
    <add 
     applicationName="MyApp" name="ActiveDirectory" 
     type="MyApp.Security.ActiveDirectoryRoleProvider" 
     domain="mydomain" groupMode="" connectionString="LDAP://myDirectoryServer.local/dc=mydomain,dc=local" 
    /> 
    </providers> 
</roleManager> 

वाह, कि कोड का एक बहुत कुछ है!

पीएस: उपरोक्त भूमिका प्रदाता के कोर पार्ट्स किसी अन्य व्यक्ति के काम पर आधारित हैं, मेरे पास लिंक आसान नहीं है लेकिन हमने इसे Google के माध्यम से पाया, इसलिए उस व्यक्ति को मूल के लिए आंशिक क्रेडिट। हमने LINQ का उपयोग करने और कैशिंग के लिए डेटाबेस की आवश्यकता से छुटकारा पाने के लिए इसे भारी रूप से संशोधित किया।

+0

यह वही लगता है जो मैं खोज रहा था। क्या आप कोई नमूना कोड प्रदान कर पाएंगे? आपके समय के लिए धन्यवाद! –

+7

ग्रेट उत्तर, आपको मेरा सम्मान मिला है – Ropstah

+0

क्या इस उदाहरण को एक प्रतिरूपण कॉन्टेक्स्ट स्थापित करने की आवश्यकता होगी? इस तरह कुछ करने की कोशिश कर रहा है लेकिन विंडोज प्रमाणीकरण के साथ। – hometoast

संबंधित मुद्दे