Jump to content

working with LDAP and Active Directory


johntp

Recommended Posts

Hey guys,

 

I have LDAP enabled on my server, and can get a connection to my ad server using my admin account, but I'm trying to make an intranet webpage where users are authenticated by Actice Directory. Any know how to do this?

Link to comment
Share on other sites

This is probably a little messy, but this is the way I do it:

 


<?php 
require('connect.inc');


$username = mysql_real_escape_string(trim(strip_tags($_POST['username'])));
$passwd = mysql_real_escape_string(trim(strip_tags($_POST['passwd'])));


  
$ds=ldap_connect("xxx.xx.xxx.xx");
if(!$ds)
{
	print "Cannot authenticate at this time...please try again soon";
	exit(0);
}

else
{
print "<br>connected";

}
   $username = "$username";
   $upasswd = "$passwd";
   $base_dn = "cn=users, dc=directory,dc=your_domain,dc=co,dc=nz";
   $rdn = "uid=$username, " . $base_dn;
   
   ldap_set_option($ldap_connect, LDAP_OPT_PROTOCOL_VERSION, 3);
   $ldapbind = ldap_bind($ds, $rdn, $upasswd);


   if ($ldapbind) 
       {
            print "<p style=\"margin-top:200px;text-align:center\">Authenticating.....</p>";

            setcookie ("username", "$username", 0, "/");

    
             if (isset($_COOKIE['welcome.php'])) {
                $target=$_COOKIE[ringi];
                Header("Location: ../intranet/$target");
             }
              else{
                    Header("Location: ../intranet/index.php?login=$username");

                    }

   }
           else{
                 print "<p style=\"margin-top:200px;text-align:center\">Authenticating.....</p>";       
                 Header("Location: logout.php");
                 }

ldap_close($ds);    //close the ldap connection

?>



Link to comment
Share on other sites

Attached is a class I use to connect and query both LDAP and Active Directory. I did not setup the Active Directory server though, so if there is some extra configuration on that end, I am no use there.

 

Usage:

<?php
  try{
    // $key -> This is a unique key to distinguish the connection, so you can recall it with getInstance() later
    // $host -> Hostname of the AD server
    // $base -> Default Base DN, something like: cn=Users,dc=Domain,dc=co,dc=com
    // $user -> Username to bind with (leave off if you want to bind anonymously)
    // $pass -> Password for bind user
    $ad = new ldap ($key,$host,$base,$user,$pass);
    $results = $ad->search('user=foobar'); //Return only keys and first values for attributes
    print_r($results);
    $results = $ad->search('user=foobar',null,true); //Return all attribute data
    print_r($results);
  } catch (ldapException $e) {
    die("LDAP Connection Failed: ".$e->getMessage());
  }
?>

 

More on the $key stuff. I usually establish my LDAP connection in an include file that get runs at the beginning of every script, and then call it later on. This is where the $key comes in handy:

<?php
  //This file gets run before every script
  //It sets up configuration stuff, etc
  require_once('ldap.class.php');
  new ldap('ad','hostname','cn=Users,dc=Domain,dc=co,dc=com','myuser','mypass');
  //No need to store the return value in a variable
?>

..and now my script...

<?php
  require_once('init.inc');
  
  function getPeople ( $cn ) {
    //Instead of doing some messy global here, we just use getInstance()
    $ad = ldap::getInstance('ad');
    return $ad->search('(cn=*'.$cn.'*)');
  }

  $people = getPeople('john');
  print_r($people);
?>

 

[attachment deleted by admin]

Link to comment
Share on other sites

Thanks, but where is this suppose to go?

 

<?php
  try{
    // $key -> This is a unique key to distinguish the connection, so you can recall it with getInstance() later
    // $host -> Hostname of the AD server
    // $base -> Default Base DN, something like: cn=Users,dc=Domain,dc=co,dc=com
    // $user -> Username to bind with (leave off if you want to bind anonymously)
    // $pass -> Password for bind user
    $ad = new ldap ($key,$host,$base,$user,$pass);
    $results = $ad->search('user=foobar'); //Return only keys and first values for attributes
    print_r($results);
    $results = $ad->search('user=foobar',null,true); //Return all attribute data
    print_r($results);
  } catch (ldapException $e) {
    die("LDAP Connection Failed: ".$e->getMessage());
  }
?>

 

Also what is ad in test.php and init.inc? should that be changed to something?

Link to comment
Share on other sites

Follow a tutorial for how to setup a standard mysql login, but instead of querying the database use something like this:

 

<?php
  require_once('ldap.class.php');
  //At this point, $user and $pass should be set
  try{
    //Change these to your configuration
    $host = 'server.domain.com';
    $base = 'cn=Users,dc=Domain,dc=co,dc=com';

    $ad = new ldap('ad_auth',$host,$base,$user,$pass);
  } catch (ldapException $e) {
    die("Authentication Failed: ".$e->getMessage());
  }
?>

Link to comment
Share on other sites

I couldn't get that script to work, but i got this one almost there.

 

<?php
//include_once("include/session.inc");
//include_once("include/functions.inc");

//PageTop();
//LocBar("Financial Department -> Login");

if( isset($_POST['login']) && isset($_POST['password']) )
{
    //LDAP stuff here.
    $username = trim($_POST['login']);
    $password = trim($_POST['password']);

    //TabTop("Authenticating...");
    $ds = ldap_connect('XXX.XXX.XXX.XXX');
    
    //Can't connect to LDAP.
    if( !ds )
    {
        echo "Error in contacting the LDAP server -- contact ";
        echo "technical services!  (Debug 1)";
        //TabBot();
       exit;
    }
    
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
    //Connection made -- bind anonymously and get dn for username.
    $bind = @ldap_bind($ds); 
    
    //Check to make sure we're bound.
    if( !bind )
    {
        echo "Anonymous bind to LDAP FAILED.  Contact Tech Services! (Debug 2)";
        //TabBot();
        exit;
    }
    
    $search = ldap_search($ds, "ou=People,dc=somthing,dc=somthing,dc=somthing,dc=com", "uid=$username");
    
    //Make sure only ONE result was returned -- if not, they might've thrown a * into the username.  Bad user!
    if( ldap_count_entries($ds,$search) != 1 )
    {
        echo "Error processing username -- please try to login again. (Debug 3)";
        redirect("./login.php");
        //TabBot();
        exit;
    }
    
    $info = ldap_get_entries($ds, $search);
    
    //Now, try to rebind with their full dn and password.
    $bind = @ldap_bind($ds, $info[0][dn], $password);
    if( !$bind || !isset($bind))
    {
        echo "Login failed -- please try again. (Debug 4)";
        redirect("./login.php");
        //TabBot();
        exit;
    }
    
    //Now verify the previous search using their credentials.
    $search = ldap_search($ds, "dc=somthing,dc=somthing,dc=somthing,dc=com", "uid=$username");
        
    $info = ldap_get_entries($ds, $search);
    if( $username == $info[0][uid][0] )
    {
        echo "Authenticated.";
        //TabBot();
        $_SESSION['username'] = $username;
        $_SESSION['fullname'] = $info[0][cn][0];
        redirect("../index.php");
        exit;
    }
    else
    {
        echo "Login failed -- please try again.";
        redirect("./login.php");
        //TabBot();
        exit;
    }
    ldap_close($ds);
    exit;
}
?>

<form action=login.php method=post name=Auth>

<?php //TabTop("Please Login"); ?>
Please log in using your user name and your
portal password:<p>

<table cellspacing=3 cellpadding=3 class=ContentBodyTable>
   <tr>
      <td>Username: </td>
      <td><input type=text name=login size=16 maxlength=15></td>
   </tr>
   <tr>
      <td>Password: </td>
      <td><input type=password name=password size=16 maxlength=15></td>
   </tr>
   <tr>
      <td colspan=2><input type=submit value=Authenticate style='width:100'></td>
   </tr>
</table>
</form>
<?php //TabBot(); ?>

<!-- Set the focus to the login text field onload. 
<script language="JavaScript" type="text/javascript">
   document.Auth.login.focus();
</script>
-->

</body>
</html>

 

I'm getting an error

Error processing username -- please try to login again. (Debug 3)

 

Any Clues?

 

Thanks in advance

Link to comment
Share on other sites

first....you are missing a couple $ signs:

    if( !$ds )

    if( !$bind )

 

my guess would be that you aren't allowed to bind anonymously. i *think* you can configure AD to allow anonymous bind, but if not, you will need to use a user (or create a system user) to do the first bind.

Link to comment
Share on other sites

Looks like that isn't the case, and bind will return true even if it doesn't really bind :(

 

But, when if I try to anonymous bind, and run a search, I get this error:

Warning: ldap_search() [function.ldap-search]: Search: Operations error in ....

 

Do you get this error? Try this code with some extra error reporting on:

 

<?php
error_reporting(E_ALL);
if( isset($_POST['login']) && isset($_POST['password']) )
{
    //LDAP stuff here.
    $host = 'XXX.XXX.XXX.XXX';
    $base = 'ou=People,dc=somthing,dc=somthing,dc=somthing,dc=com';
    $username = trim($_POST['login']);
    $password = trim($_POST['password']);

    //TabTop("Authenticating...");
    $ds = ldap_connect($host);
    
    //Can't connect to LDAP.
    if( !$ds )
    {
        echo "Error in contacting the LDAP server -- contact ";
        echo "technical services!  (Debug 1)";
        //TabBot();
       exit;
    }
    
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
    //Connection made -- bind anonymously and get dn for username.
    $bind = ldap_bind($ds); 
    
    //Check to make sure we're bound.
    if( !$bind )
    {
        echo "Anonymous bind to LDAP FAILED.  Contact Tech Services! (Debug 2)";
        //TabBot();
        exit;
    }
    $search = ldap_search($ds, $base, "uid=$username");

    //Make sure only ONE result was returned -- if not, they might've thrown a * into the username.  Bad user!
    if( !$search || ldap_count_entries($ds,$search) != 1 )
    {
        echo "Error processing username -- please try to login again. (Debug 3)";
        redirect("./login.php");
        //TabBot();
        exit;
    }
    
    $dn = ldap_get_dn($ds,ldap_first_entry($ds, $search));
    
    //Now, try to rebind with their full dn and password.
    $bind = ldap_bind($ds, $dn, $password);
    if( !$bind )
    {
        echo "Login failed -- please try again. (Debug 4)";
        redirect("./login.php");
        //TabBot();
        exit;
    }
    
    //Now verify the previous search using their credentials.
    $search = ldap_search($ds, $base, "uid=$username");
        
    list($user) = ldap_get_entries($ds, $search);
    if( $username == $user['uid'][0] )
    {
        echo "Authenticated.";
        //TabBot();
        $_SESSION['username'] = $username;
        $_SESSION['fullname'] = $info[0][cn][0];
        redirect("../index.php");
        exit;
    }
    else
    {
        echo "Login failed -- please try again.";
        redirect("./login.php");
        //TabBot();
        exit;
    }
    ldap_close($ds);
    exit;
}
?>

<form method="post" name="Auth">

<?php //TabTop("Please Login"); ?>
Please log in using your user name and your
portal password:<p>

<table cellspacing=3 cellpadding=3 class=ContentBodyTable>
   <tr>
      <td>Username: </td>
      <td><input type=text name=login size=16 maxlength=15></td>
   </tr>
   <tr>
      <td>Password: </td>
      <td><input type=password name=password size=16 maxlength=15></td>
   </tr>
   <tr>
      <td colspan=2><input type=submit value=Authenticate style='width:100'></td>
   </tr>
</table>
</form>
<?php //TabBot(); ?>

<!-- Set the focus to the login text field onload. 
<script language="JavaScript" type="text/javascript">
   document.Auth.login.focus();
</script>
-->

</body>
</html>

Link to comment
Share on other sites

well...couple questions...

 

Are you sure your base is correct?

Are you sure your username field is uid?

Did you try doing a generic search with something like this:

$search = ldap_search($ds, $base, "uid=*");
print_r ldap_get_entries($ds, $search);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.