Re: Authenticate through AD
From: Hernan de Lahitte (hernan_at_lagash.com)
Date: 01/13/04
- Next message: Joe Kaplan \(MVP - ADSI\): "Re: Active Directory and Dotnet...."
- Previous message: Yaseen: "Active Directory and Dotnet...."
- In reply to: Laurent Rivillon: "Re: Authenticate through AD"
- Next in thread: Laurent Rivillon: "Re: Authenticate through AD"
- Reply: Laurent Rivillon: "Re: Authenticate through AD"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] [ attachment ]
Date: Tue, 13 Jan 2004 12:14:39 -0300
Ok. Here it is:
using System;
using System.Collections;
using System.Security.Principal;
using System.DirectoryServices;
using System.Security;
using System.Globalization;
using System.Diagnostics;
using Framework.Security.Access;
namespace Framework.Services.Library
{
/// <summary>
/// Provides static methods that supply helper utilities for manipulating
active directory and LDPA access. This class cannot be inherited.
/// </summary>
public sealed class AdHelper
{
#region Private objects & Constructors
private static AuthenticationTypes defaultAuthType =
AuthenticationTypes.Secure |
AuthenticationTypes.Sealing; // |
//AuthenticationTypes.Signing;
private static AuthenticationTypes threaduserAuthType =
AuthenticationTypes.Secure;
private static string defaultRootPath = String.Empty;
static AdHelper()
{
try
{
using(DirectoryEntry root = new DirectoryEntry("GC:"))
{
//RefreshCache(root);
//Gets ths GC enumerator
IEnumerator ie = root.Children.GetEnumerator();
if(ie.MoveNext())
{
defaultRootPath = ((DirectoryEntry)ie.Current).Path;
}
else
{
//Get the default root.
using(DirectorySearcher DSESearcher = new DirectorySearcher())
{
defaultRootPath = DSESearcher.SearchRoot.Path;
}
}
}
}
catch(Exception ex)
{
LogHelper.Publish("Exception in AdHelper constructor.", ex,
LogHelper.LogEntryType.Warning);
}
}
private static DirectoryEntry GetRootActiveDirectory()
{
return GetRootActiveDirectory(null);
}
private static DirectoryEntry GetRootActiveDirectory(FrameworkCredential
credentials)
{
DirectoryEntry root = new DirectoryEntry();
if( credentials != null && credentials.Password.Length > 0 )
{
root.Username = credentials.PrincipalAccount;
root.Password = credentials.Password;
root.AuthenticationType = defaultAuthType;
}
else
{
root.AuthenticationType = AdHelper.threaduserAuthType;
}
root.Path = defaultRootPath;
return root;
}
#endregion
#region Public methods
/// <summary>
/// Returns a DirectoryEntry object from a windows SAM account name.
/// </summary>
/// <param name="userAccount">Windows SAM account name.</param>
/// <returns>DirectoryEntry object.</returns>
public static DirectoryEntry GetUserFromWinAccount(string userAccount)
{
using(FrameworkCredential credentials = new
FrameworkCredential(userAccount))
{
return GetUserFromWinAccount(credentials);
}
}
/// <summary>
/// Returns a DirectoryEntry object from a windows SAM account name.
/// </summary>
/// <param name="credentials">See <see cref="FrameworkCredential"/>.</param>
/// <returns>Objeto DirectoryEntry.</returns>
public static DirectoryEntry GetUserFromWinAccount(FrameworkCredential
credentials)
{
if(credentials == null)
throw new ArgumentNullException("credentials");
DirectoryEntry retVal = null;
//Bind to global catalog
using(DirectoryEntry gc_root = GetRootActiveDirectory(credentials))
{
//Search by user name
using(DirectorySearcher searcher = new DirectorySearcher(gc_root))
{
#region Define Search
searcher.Filter =
String.Format("(&(objectCategory=person)(objectClass=user)(SAMAccountName={0
}))", credentials.UserName);
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("AdsPath");
searcher.PropertiesToLoad.Add("displayName");
searcher.PropertiesToLoad.Add("mail");
#endregion
#region Find & retrive results
using(SearchResultCollection results = searcher.FindAll())
{
if( results.Count>0 )
{
if( credentials.Domain.Length == 0 )
{
retVal = results[0].GetDirectoryEntry();
}
else
{
//Returns results for that particular domain
string compare = string.Concat("dc=", credentials.Domain, ",");
int rescount = results.Count;
for (int i = 0; i < rescount; i++)
{
SearchResult sr = results[i];
string adspath = sr.Properties["ADsPath"][0] as string;
if(FrameworkUtility.CaseInsensitiveIndexOf(adspath, compare)!=-1 )
{
retVal = sr.GetDirectoryEntry();
break;
}
}
}
}
}
#endregion
} // searcher
} // GetRootActiveDirectory
if(retVal == null || retVal.NativeObject == null)
throw new SecurityException(String.Format("The user {0} is trying to
authenticate to an invalid domain.", credentials.PrincipalAccount));
return retVal;
}
/// <summary>
/// Loads the property values for this directory entry into the property
cache.
/// </summary>
/// <param name="entry">DirectoryEntry object.</param>
/// <remarks>
/// In order to mitigate this exception,
/// 0x8000500C - "The Active Directory datatype cannot be converted to/from
a native DS datatype"
/// See Q241981
(http://support.microsoft.com/default.aspx?scid=kb;en-us;241981)
/// </remarks>
public static void RefreshCache(DirectoryEntry entry)
{
try
{
if(entry != null)
{
if(entry.SchemaEntry != null) entry.SchemaEntry.RefreshCache(); //force
refresh of schema
entry.RefreshCache(); //force reload of cache info
}
}
catch (Exception e)
{
LogHelper.Publish(String.Format("Exception in DirectoryEntry:
{0}{1}SchemaEntry: {2}",entry.Path, Environment.NewLine,
entry.SchemaEntry.Path), e);
}
}
#endregion
}
}
-- Hernan de Lahitte - MSDE Lagash Systems S.A. - Buenos Aires, Argentina http://www.lagash.com "Laurent Rivillon" <anonymous@discussions.microsoft.com> wrote in message news:5B4589B4-5376-4303-B1C4-D1F2C227C3E2@microsoft.com... > Thanks for your help, but I can't see the file you're talking about. > Could you please copy/paste the content of this file.
- Next message: Joe Kaplan \(MVP - ADSI\): "Re: Active Directory and Dotnet...."
- Previous message: Yaseen: "Active Directory and Dotnet...."
- In reply to: Laurent Rivillon: "Re: Authenticate through AD"
- Next in thread: Laurent Rivillon: "Re: Authenticate through AD"
- Reply: Laurent Rivillon: "Re: Authenticate through AD"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] [ attachment ]