?
Solved

PHP authentication against Microsoft Active directory then returning users' group

Posted on 2004-11-16
4
Medium Priority
?
311 Views
Last Modified: 2008-02-01
We had the following script running a on redhat linux box w/php 4.x-apache 1.3.x authenicating a user against a NT4 domain controller which worked great until the recent upgrade to Active Directory. Not only does the script auth against the domain controller but if the user exists then this script determines which of the three groups the user is in. I have googled everywhere but not found much that is useful besides some ldap info which have posted the links to below our original script. I'm looking for a working script not a bunch of links, i'm not a pro with microsofts server stuff so a simple script that can do the same as our previous one would be great, thanks.

<?PHP
include("connect.php3");
function domainAuth($login, $pass){
            $primary_svr = "ufdc01.ad.ufl.edu";
            $domain = "UFAD";
            $group = "FRE";
            $authToNTDomain = validate($primary_svr, $domain, $group, $login, $pass);
            //echo "Class: authToNTDomain: $authToNTDomain<BR>";
            //echo smbauth_err2str($authToNTDomain) . "<BR>";
            if ($authToNTDomain == "0"  && $login != "" && $pass != "") {
                  return true;
                  //$this->authedToDomain = true;
                  //echo "this->authedToDomain = true<BR>";
            } else {
                  return false;
                  //$this->authedToDomain = false;
                  //echo "this->authedToDomain = false<BR>";
            }
}

function getGroup($login, $pass){
            $server = "ufdc01.ad.ufl.edu";
            $domain = "UFAD";
            $groups = getUserGroups($server, $domain, $login, $pass);

            //$err = err2str();
            //echo "error: $err<BR>";            
            $numItems = getNumItems($groups);
            $i = 0;
            while($i < $numItems){
                  $item = getItem($groups, $i);
                  //echo "$item<BR>";
                  $groupList[] = $item;
                  $i++;
            }
            
            $numGroups = count($groupList);
            for($g=0;$g < $numGroups;$g++){
                  //echo  "list: $groupList[$g] <BR>";
                  if ($groupList[$g] == "IF-FREDStaff"){
                        $group = "staff";
                        return $group;
                  } elseif ($groupList[$g] == "IF-FREDGrad"){
                        $group = "student";
                        return $group;
                  } elseif ($groupList[$g] == "IF-FREDFaculty"){
                        $group = "faculty";
                        return $group;
                  }
            }

            return false;

}


function inFRE($ID){
            $query = "SELECT * FROM directory WHERE username='$ID'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 1 ) {
                  $located= mysql_num_rows($result);
                  $data = mysql_fetch_object($result);
            } else {
                  $query = "SELECT * FROM students WHERE ID='$ID'";
                  $result = mysql_query($query);
                  $located= mysql_num_rows($result);
                  $data = mysql_fetch_object($result);
            }

            if($located){
                  return true;
                  //$this->inFRE = true;
            } else {
                  return false;
                  //$this->inFRE = false;
            }
}




function hasBios($ID){
      $query = "SELECT * FROM directory WHERE username='$ID'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 1 ) {
                  $data = mysql_fetch_object($result);
                  $type = $data->type;
            } else {
                  $query = "SELECT * FROM students WHERE ID='$ID'";
                  $result = mysql_query($query);
                  if(mysql_num_rows($result) == 1 ) {
                        $type = "Student";
                  }
            }      
                        

      if ($type == "Student"){
          $database = "student_bios";
      } elseif ($type == "Faculty"){
          $database = "faculty_bios";
      } elseif ($type == "Staff"){
          $database = "staff_bios";
      }

      $query = "SELECT bios_ID FROM $database WHERE bios_ID='$ID'";
      $result = mysql_query($query);
      $hasBios = mysql_num_rows($result);
      return $hasBios;
}


function createSession($login_user){
      global $HTTP_REFERER;
      session_id();
      session_start();
      $_SESSION["Username"] = "$login_user";
      $_SESSION["LoggedIn"] = 1;
      $sessionID = session_id();
      //SetCookie("sessionID", $sessionID);
      Header("Location: $HTTP_REFERER");
      return 1;
}


function isSupport($login, $pass){
                $server = "nt-pdc";
                $domain = "ifasdom";

                $groups = getUserGroups($server, $domain, $login, $pass);
                //$err = err2str();  
                //echo "error: $err<BR>";
                $numItems = getNumItems($groups);
                $i = 0;
                while($i < $numItems){
                        $item = getItem($groups, $i);
                        //echo "$item<BR>";
                        $groupList[] = $item;
                        $i++;
                }
                       
                $numGroups = count($groupList);
                for($g=0;$g < $numGroups;$g++){
                        //echo  "list: $groupList[$g] <BR>";
                        if ($groupList[$g] == "FREDSupport"){
                              return true;
                        //will return true and exit if found as support
                        }
                }
            // false if after looking through groupList array and not found as FREDSupport  
                return false;
}


?>

http://www.markround.com/ldap.html
http://www.developer.com/lang/php/article.php/3100951
http://www.experts-exchange.com/Web/Web_Languages/PHP/PHP_Windows/Q_21043386.html

0
Comment
Question by:adamshields
  • 2
  • 2
4 Comments
 
LVL 1

Expert Comment

by:ryan-h
ID: 12611912
can u post any errors you are receiving? either from php/apache, the error_log file or the domain controllers event logs. and if not can u tell us what the script is 'now' doing if anything?

I don't have a domain controller handy to play with so i'll need a bit more info
0
 
LVL 3

Author Comment

by:adamshields
ID: 12621211
Ok, I've got users authenicating agaisnt the AD server now and it's successfully returning one of the three groups. Now I have a new problem.

Go here http://www.fred.ifas.ufl.edu/bios/createlogin.php and try to login just using the username 'rsreese' and you'll see a mysql error

Duplicate entry '' for key 1

Here is my table layout:

CREATE TABLE `staff_bios` (
  `bios_ID` varchar(33) NOT NULL default '',
  `Responsibilities` text,
  `Summary` text,
  `Current_Projects` text,
  `Web_Links` text,
  `Degrees` text,
  `Interests` text,
  `Awards_and_Achievements` text,
  `Last_Modified` int(11) default NULL,
  PRIMARY KEY  (`bios_ID`),
  UNIQUE KEY `bios_ID` (`bios_ID`)
) TYPE=MyISAM;

Should I move this over to mysql/php?


0
 
LVL 1

Accepted Solution

by:
ryan-h earned 1000 total points
ID: 12621674
the error says u can't have duplicates in a column defined as unique.

You either need to specify the value of bios_ID in your query or set your primary key (bios_ID) to type INT and auto_increment

I'm making the assuption that bios_ID is the netbios name in which case you will need to add a new ID field and use that as the primaray key if you want an auto increment. something like this (not tested)

CREATE TABLE `staff_bios` (
  `id` int(11) NOT NULL auto_increment '',
  `bios_ID` varchar(33) NOT NULL'',
  `Responsibilities` text,
  `Summary` text,
  `Current_Projects` text,
  `Web_Links` text,
  `Degrees` text,
  `Interests` text,
  `Awards_and_Achievements` text,
  `Last_Modified` int(11) default NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `bios_ID` (`bios_ID`)
) TYPE=MyISAM;
0
 
LVL 3

Author Comment

by:adamshields
ID: 12655586
Ok, well I figure out what I had to do. First off you must have some type of rights to view the users group information in the AD schemea. The following is the edited script.:


<?php
error_reporting(E_ALL);
      mysql_connect("localhost","user","pass");
      mysql_select_db("database");



function domainAuth($login, $pass){      
      $ldap_host = "ad.ufl.edu";
      $base_dn = "OU=FRE,OU=IFAS,OU=People,OU=UF,DC=ad,DC=ufl,DC=edu";
      
      $domain = "@ufl.edu";
      $ldap_user = $login.$domain;
      $ldap_pass = $pass;

//      $connect = ldap_connect( $ldap_host, $ldap_port)
      $connect = ldap_connect( $ldap_host)
       or exit("Could not connect to LDAP server");

      // required to search AD, according to note in PHP manual notes
      ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
      ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);

      $bind = ldap_bind($connect, $ldap_user, $ldap_pass)
           or exit("Could not bind to $ldap_host");

      echo "Successful bind to $ldap_host with $bind<br><br>\n";
      
ldap_unbind($connect);
}



function getGroup($login){

      $ldap_host = "ad.ufl.edu";
      $base_dn = "OU=FRE,OU=IFAS,OU=People,OU=UF,DC=ad,DC=ufl,DC=edu";
      $filter = "(CN=$login)";
      $ldap_user = "user@withadmin.rights.com";
      $ldap_pass = "thepass";


$connect = ldap_connect( $ldap_host)
       or exit("Could not connect to LDAP server");

      // required to search AD, according to note in PHP manual notes
      ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
      ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);

      $bind = ldap_bind($connect, $ldap_user, $ldap_pass)
           or exit("Could not bind to $ldap_host");

      echo "Successful bind to $ldap_host with $bind<br><br>\n";

      $read = ldap_search($connect, $base_dn, $filter)
           or exit("Unable to search ldap server");

      $info = ldap_get_entries($connect, $read);
      echo $info["count"]." entries returned for $filter<br><br>\n";

      $ii=0;
      for ($i=0; $ii<$info[$i]["count"]; $ii++){
            $data = $info[$i][$ii];
            if ($data == "memberof") {
                  $total_memberof = (count($info[$i][$data]));
                  echo "Total memberof entries returned: $total_memberof<br><br>\n";
                  $total = 0;
                  $total = count($info[$i][$data]);
                  $jj=0;
                  for ($jj=0; $jj<$total; $jj++) {
                        if ($info[$i][$data][$jj] == "CN=IF-FREDStaff,OU=Groups,OU=FRE,OU=Campus,OU=-Co-Managed,OU=IFAS,OU=Departments,OU=UF,DC=ad,DC=ufl,DC=edu") {
                              //echo "<b>Got Staff Match</b> ";
                              $group = "IF-FREDStaff";
                              return $group;
                        } elseif (($info[$i][$data][$jj] == "CN=IF-FREDFaculty,OU=Groups,OU=FRE,OU=Campus,OU=-Co-Managed,OU=IFAS,OU=Departments,OU=UF,DC=ad,DC=ufl,DC=edu") && $group == "") {
                              //echo "<b>Got Faculty Match</b> ";
                              $group = "faculty";
                              return $group;
                        } elseif (($info[$i][$data][$jj] == "CN=IF-FREDGrad,OU=Groups,OU=FRE,OU=Campus,OU=-Co-Managed,OU=IFAS,OU=Departments,OU=UF,DC=ad,DC=ufl,DC=edu") && $user_type == "") {
                              //echo "<b>Got Students Match</b> ";
                              $group = "student";
                              return $group;
                        }
                  //      echo $i." ".$ii." ".$jj."
// ".$data.":&nbsp;&nbsp;".$info[$i][$data][$jj]."<br>\n";
                  }
            }
      }

      ldap_unbind($connect);
}

function inFRE($ID){
            $query = "SELECT * FROM directory WHERE username='$ID'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 1 ) {
                  $located= mysql_num_rows($result);
                  $data = mysql_fetch_object($result);
            } else {
                  $query = "SELECT * FROM students WHERE ID='$ID'";
                  $result = mysql_query($query);
                  $located= mysql_num_rows($result);
                  $data = mysql_fetch_object($result);
            }

            if($located){
                  return true;
                  //$this->inFRE = true;
            } else {
                  return false;
                  //$this->inFRE = false;
            }
}




function hasBios($ID){
      $query = "SELECT * FROM directory WHERE username='$ID'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 1 ) {
                  $data = mysql_fetch_object($result);
                  $type = $data->type;
            } else {
                  $query = "SELECT * FROM students WHERE ID='$ID'";
                  $result = mysql_query($query);
                  if(mysql_num_rows($result) == 1 ) {
                        $type = "Student";
                  }
            }      
                        

      if ($type == "Student"){
          $database = "student_bios";
      } elseif ($type == "Faculty"){
          $database = "faculty_bios";
      } elseif ($type == "Staff"){
          $database = "staff_bios";
      }

      $query = "SELECT bios_ID FROM $database WHERE bios_ID='$ID'";
      $result = mysql_query($query);
      $hasBios = mysql_num_rows($result);
      return $hasBios;
}


function createSession($login_user){
      global $HTTP_REFERER;
      session_id();
      session_start();
      $_SESSION["Username"] = "$login_user";
      $_SESSION["LoggedIn"] = 1;
      $sessionID = session_id();
      //SetCookie("sessionID", $sessionID);
      Header("Location: $HTTP_REFERER");
      return 1;
}

?>
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses

579 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question