I have the goal of authenticate MySQL users with an LDAP server, currently, employees of my company are authenticated in several services (ftp, ssh, svn) through my LDAP server, except MySQL. (As you can imagine, I need to add manually every user in MySQL, a very tedious task).

In this post I only leave the example with LDAP authentication.

Installing necessary packages


yum groupinstall 'Development Tools'
yum install openldap-devel

Source ldapClient.c

#include <stdio.h>
#include <ldap.h>
/* LDAP Server settings */
#define LDAP_SERVER "ldap://nafiux.com:389"
int
main( int argc, char **argv )
{
LDAP        *ld;
int        rc;
char        bind_dn[100];

/* Get username and password */
if( argc != 3 )
{
perror( "invalid args, required: username password" );
return( 1 );
}
sprintf( bind_dn, "cn=%s,ou=People,dc=nafiux,dc=com", argv[1] );
printf( "Connecting as %s...\n", bind_dn );

/* Open LDAP Connection */
if( ldap_initialize( &ld, LDAP_SERVER ) )
{
perror( "ldap_initialize" );
return( 1 );
}

/* User authentication (bind) */
rc = ldap_simple_bind_s( ld, bind_dn, argv[2] );
if( rc != LDAP_SUCCESS )
{
fprintf(stderr, "ldap_simple_bind_s: %s\n", ldap_err2string(rc) );
return( 1 );
}
printf( "Successful authentication\n" );
ldap_unbind( ld );
return( 0 );
}

Compile and build

gcc ldapClient.c -o ldapClient -lldap

Run

7 Thoughts on “LDAP C Client Authentication Example (with OpenLDAP)

  1. Works nicely – thanks! I am on FreeBSD 9.1 with OpenLDAP 2.4, and LDAP* ld = ldap_open(.. ) causes segmentation errors. But ldap_initialize(&ld,.. ) works as expected. Great example.

  2. Thank you very much, it helped me for the creation of a login page using LDAP in an iOS application with Xcode.

  3. I have an another question. I was able to find the user on LDAP server. Now while trying to authenticate the user, I ended up with some complexities. I was doing a “ldap_compare_s” for the password and it apparently failed when the password was encrypted at the LDAP server.

    On a suggestion from stackoverflow.com (http://stackoverflow.com/questions/16168293/how-to-do-password-authentication-for-a-user-using-ldap) I tried binding the user after the search and it was successful.

    Is this the correct way to test a user credentials via LDAP?

  4. I have an another question. I was able to find the user on LDAP server. Now while trying to authenticate the user, I ended up with some complexities. I was doing a “ldap_compare_s”

  5. Thanks for the example program. I could easily get it working. I am currently writing a client application to authenticate user via LDAP. This was helpful.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation