2011-12-03 2 views
0

그래서 일부 LDAP 값을 잡고 암호화를 사용하여 데이터베이스에 삽입하려고합니다. 삽입 작동하지만 사용자가 여전히 그룹의 일부인지 확인하고 DB에서 제거하지 않으면 새 사용자가 추가되면 기존 사용자를 삽입하는 대신 삽입합니다. 이에 대한 모범 사례에 대한 지침을 줄 수 있습니까? 나는 테이블을 자르고 다시 삽입하지 않는 것을 선호합니다.프로그래밍 방식으로 SQL에서 LDAP 사용자를 업데이트하고 삭제하는 방법은 무엇입니까?

 try 
     { 
      /* Connection to Active Directory */ 
      DirectoryEntry deBase = new DirectoryEntry("LDAP://" + txtLDAP.Text + ":" + txtLDapPort.Text + "/" + txtBadeDN.Text, txtUsername.Text, txtPassword.Text, AuthenticationTypes.Secure); 

      /* Directory Search*/ 
      DirectorySearcher dsLookForGrp = new DirectorySearcher(deBase); 
      dsLookForGrp.Filter = String.Format("(cn={0})", txtGroup.Text); 
      dsLookForGrp.SearchScope = SearchScope.Subtree; 
      dsLookForGrp.PropertiesToLoad.Add("distinguishedName"); 
      SearchResult srcGrp = dsLookForGrp.FindOne(); 

      /* Directory Search 
      */ 
      DirectorySearcher dsLookForUsers = new DirectorySearcher(deBase); 
      dsLookForUsers.Filter = String.Format("(&(objectCategory=person)(memberOf={0}))", srcGrp.Properties["distinguishedName"][0]); 
      dsLookForUsers.SearchScope = SearchScope.Subtree; 
      dsLookForUsers.PropertiesToLoad.Add("objectSid"); 
      dsLookForUsers.PropertiesToLoad.Add("sAMAccountName"); 
      SearchResultCollection srcLstUsers = dsLookForUsers.FindAll(); 

      StringBuilder sbUsers = new StringBuilder(); 

      foreach (SearchResult sruser in srcLstUsers) 
      { 
       SecurityIdentifier sid = new SecurityIdentifier((byte[])sruser.Properties["objectSid"][0], 0); 
       string ConnString = "ConnectionString Removed"; 
       string SqlString = "spInsertADAuthorization"; 
       using (OleDbConnection conn = new OleDbConnection(ConnString)) 
       { 
        using (OleDbCommand cmd = new OleDbCommand(SqlString, conn)) 
        { 
         cmd.CommandType = CommandType.StoredProcedure; 
         cmd.Parameters.AddWithValue("AD_Account", SpartaCrypto.SpartaEncryptAES(sruser.Properties["sAMAccountName"][0].ToString(), "thisisasharedsecret")); 
         cmd.Parameters.AddWithValue("AD_SID", SpartaCrypto.SpartaEncryptAES(sid.ToString(), "thisisasharedsecret")); 
         cmd.Parameters.AddWithValue("AD_EmailAddress", "[email protected]"); 
         cmd.Parameters.AddWithValue("DateImported", DateTime.Now.ToString()); 
         cmd.Parameters.AddWithValue("Active", 1); 
         conn.Open(); 
         cmd.ExecuteNonQuery(); 
         conn.Close(); 
        } 
       } 
       lblResults.Text = srcLstUsers.Count + " Users granted access."; 
      } 
     } 

     catch (Exception ex) 
     { 
      if (ex.Message.Contains("Logon failure")) 
      { 
       lblResults.Text = "Logon Failure. Check your username or password."; 
      } 

      if (ex.Message.Contains("The server is not operational")) 
      { 
       lblResults.Text = "LDAP Error. Check your hostname or port."; 
      } 
      if (ex.Message.Contains("Object reference not set to an instance of an object")) 
      { 
       lblResults.Text = "LDAP Error. Check your hostname, port, or group name and try again."; 
      } 


     } 

답변

0

당신이 .NET 3.5 및 최대에있어 있기 때문에, 당신은 System.DirectoryServices.AccountManagement (S.DS.AM) 네임 스페이스를 확인해야합니다. 여기에 대한 모든 읽기 :

// create your domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the first name (GivenName) of "Bruce" 
UserPrincipal qbeUser = new UserPrincipal(ctx); 
qbeUser.GivenName = "Bruce"; 

// create your principal searcher passing in the QBE principal  
PrincipalSearcher srch = new PrincipalSearcher(qbeUser); 

// find all matches 
foreach(var found in srch.FindAll()) 
{ 
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....   
} 

:

당신은 당신의 검색을 할 수있는 PrincipalSearcher하고 "쿼리별로 예를 들어"주체를 사용할 수 있습니다 단일 프린시 펄과 함께 작업 할 때 프로그래밍 인터페이스는 훨씬 편리합니다.

// find a user 
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); 

if(user != null) 
{ 
    // do something here... you can access most of the commonly used properties easily 
    user.GivenName = "...."; 
    user.Surname = "......"; 
    user.SamAccountName = "....."; 
} 

// find the group in question 
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere"); 

// if found.... 
if (group != null) 
{ 
    // iterate over members 
    foreach (Principal p in group.GetMembers()) 
    { 
     Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName); 
     // do whatever you need to do to those members 
    } 
} 

새로운 S.DS.AM을 사용하면 실제로 이 (가) 더 쉽게을 AD에서 사용자 및 그룹과 놀 수 있습니다!

+0

감사합니다. 감사합니다. 그러나이 생각에서 얻으려고하는 것은 현재 그룹에 가입 한 사용자 삽입을 관리하고 이미 DB에있는 사용자를 다시 삽입하지 않는 것입니다. 또한 DB에 있지만 더 이상 그룹의 일부가 아닌 사용자를 제거합니다. –

관련 문제