Class : valider un login et mot de passe sur active directory (asp.net, c#)

Contenu du snippet

Je n'ai absolument pas réalisé le code ! Mais comme j'ai mis un peu de temps à trouver je le mais ici !

Pour plus de renseignement consulter les docs du msdn ici :

POUR LA CLASS DE CONNECTION :
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT02.asp

POUR L'EXPLICATION DU PATH :
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdirectoryservicesdirectoryentryclasspathtopic.asp

Source / Exemple :


using System;
using System.Collections;
using System.DirectoryServices;

namespace FormsAuthAD
{
	/// <summary>
	/// Description résumée de ActiveDirectory.
	/// </summary>
	public class LdapAuthentication
	{
		public LdapAuthentication()
		{
			//
			// TODO : ajoutez ici la logique du constructeur
			//
		}

		public LdapAuthentication( string path )
		{
			_path = path;
		}

		private string _path;
		private string _filterAttribute;

		public bool IsAuthenticated(string domain, string username, string pwd)
		{
			string domainAndUsername = domain + @"\" + username;
			DirectoryEntry entry = new DirectoryEntry( _path, 
				domainAndUsername,
				pwd);

			try
			{ 
				// Bind to the native AdsObject to force authentication.
				Object obj = entry.NativeObject;
				DirectorySearcher search = new DirectorySearcher(entry);
				search.Filter = "(SAMAccountName=" + username + ")";
				search.PropertiesToLoad.Add("cn");
				SearchResult result = search.FindOne();
				if(null == result)
				{
					return false;
				}
				// Update the new path to the user in the directory
				_path = result.Path;
				_filterAttribute = (String)result.Properties["cn"][0];
			}
			catch (Exception ex)
			{
				throw new Exception("Error authenticating user. " + ex.Message);
			}
			return true;
		}

		
	}
}

// UTILISATION DE LA CLASS EXEMPLE :
bool bResult = false;
LdapAuthentication MyAD = new LdapAuthentication( "LDAP://AdresseOuNomduserveurdedomaine" );

try
{
       bResult = MyAD.IsAuthenticated( "Nomdudoaine","login", "Motdepasse" );		
}
catch( Exception ExErreur )
{
     messageLabel.Text = "Erreur Active Directory : "+ExErreur.Message;
}

Conclusion :


PS : Tester sous Windows 2000

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.