Authenticating an LDAP Client

The bind operation identifies the person (or device or application) that is trying to connect to the server by providing a distinguished name and some type of authentication credential, such as a password. The exact credentials depend on the authentication method being used. You can also bind anonymously by passing NULL parameters.

The ldap_simple_bind functions use a clear text password for authentication. Call the ldap_bind or ldap_bind_s function to use authentication services, such as the Windows NT® LAN Manager (NTLM), distributed password authentication, or the Generic Security Services API. Note that ldap_bind is not supported for Negotiate.

The following code example shows how to bind to a server using NTLM.

#include <windows.h>
#include <winldap.h>
#include <winber.h>
#include <tchar.h>

LPTSTR szServer[64], szUserName[32], szPassword[32], szDomain[64], szOutput[128];
WORD wPort;
ULONG ulAuthMethod, ulLdapError;
LDAP *ld;
SEC_WINNT_AUTH_IDENTITY AuthId;

_tcscpy( szServer, TEXT("dc.microsoft.com") );
wPort = LDAP_PORT;

_tcscpy( szUserName, TEXT("Admin") );
_tcscpy( szPassword, TEXT("Password") );
_tcscpy( szDomain, TEXT("MICROSOFT") );

ulAuthMethod = LDAP_AUTH_NTLM;

// ...

// Set up AuthId for NTLM authentication
AuthId.User = _tcslen(szUserName) ? szUserName : NULL;
AuthId.UserLength = _tcslen(szUserName);
AuthId.Domain = _tcslen(szDomain) ? szDomain : NULL;
AuthId.DomainLength = _tcslen(szDomain);
AuthId.Password = _tcslen(szPassword) ? szPassword : NULL;
AuthId.PasswordLength = _tcslen(szPassword);
#ifdef UNICODE
AuthId.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
#else
AuthId.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
#endif

ld = ldap_init( szServer, wPort );
if( ld == NULL )
{
   wsprintf (szOutput, TEXT("ldap_init() failed. Error: %u"), LdapGetLastError());
   MessageBox (NULL, szOutput, TEXT("Error"), MB_OK);
   return FALSE;
}

// use v3 Client
ULONG version = LDAP_VERSION3;
ulLdapError = ldap_set_option( ld, LDAP_OPT_VERSION, &version );
if( ulLdapError != LDAP_SUCCESS )
{
   wsprintf (szOutput, TEXT("ldap_set_option() failed. Error: %u"), ulLdapError);
   MessageBox (NULL, szOutput, TEXT("Error"), MB_OK);
   ldap_unbind( ld );
   return FALSE;
}

ulLdapError = ldap_bind_s( 
ld, 
(ulAuthMethod == LDAP_AUTH_SIMPLE) ? AuthId.User : NULL,
(ulAuthMethod == LDAP_AUTH_SIMPLE) ? AuthId.Password : (TCHAR *) &AuthId, 
ulAuthMethod );

if( ulLdapError != LDAP_SUCCESS )
{
   wsprintf (szOutput, TEXT("ldap_bind_s() failed. Error: %u"), ulLdapError);
   MessageBox (NULL, szOutput, TEXT("Error"), MB_OK);
   ldap_unbind( ld );
   return FALSE;
}

// Successfully bound to the server!

// Request information from the directory and/or modify it...

ldap_unbind( ld );
return TRUE; 

See Also

Using the LDAP API

 Last updated on Friday, April 09, 2004

© 1992-2003 Microsoft Corporation. All rights reserved.