|
-
Jun 21st, 2011, 03:51 PM
#1
[RESOLVED] Need to understand this, PHP connecting to LDAP
I have a php page from the previous developer that I would like to convert into a new .Net webapp so I can expand it later.
It connects to an LDAP server, loops through the properties and spits it out on the page as a table. My biggest problem is, I can't seem to get .Net to connect to the LDAP server even though I'm building the connection url following a few examples, I keep getting either a "Invalid username and password" or "Unexpected Error from COM" when I try. I've attached the PHP file here & here's the .Net code I have so far:
Code:
Friend Module LDAPModule
Friend Const g_LDAP_Password As String = "password"
Friend Const g_LDAP_Server As String = "server"
'Friend Const g_LDAPrdn As String = "cn=root"
Friend Const g_LDAP_Connection As String = "LDAP://{0}/cn=users,dc=ecop,dc=com"
Friend Function GetEmptyUsersTable() As DataTable
Dim Output As New DataTable("LDAP_Users")
With Output.Columns
.Add("UserID", GetType(String))
.Add("Password", GetType(String))
.Add("FirstName", GetType(String))
.Add("LastName", GetType(String))
.Add("EmpType", GetType(String))
.Add("PhoneNumber", GetType(String))
.Add("EmailAddress", GetType(String))
End With
Return Output
End Function
End Module
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Call BindGrid(GetAllPortalUsers())
End Sub
Private Function GetAllPortalUsers() As DataTable
Dim PortalUsers As DataTable = GetEmptyUsersTable()
Dim oSearcher As New DirectorySearcher(New DirectoryEntry(String.Format(g_LDAP_Connection, String.Empty, g_LDAP_Password, AuthenticationTypes.Anonymous)))
Dim oResults As SearchResultCollection
Dim oResult As SearchResult
'Dim RetArray As New Hashtable()
Try
oSearcher.PropertiesToLoad.Add("uid=*")
oResults = oSearcher.FindAll
Dim dr As DataRow
For Each oResult In oResults
If Not oResult.GetDirectoryEntry().Properties("cn").Value.ToString = String.Empty Then
dr = PortalUsers.NewRow
dr("UserID") = oResult.GetDirectoryEntry().Properties("uid").Value
'dr("Password") =
'dr("EmpType") =
'dr("FirstName") =
'dr("LastName") =
'dr("PhoneNumber") =
'dr("EmailAddress") =
PortalUsers.Rows.Add(dr)
dr = Nothing
'RetArray.Add(oResult.GetDirectoryEntry().Properties("uid").Value, oResult.GetDirectoryEntry().Properties("cn").Value)
End If
Next
Catch ex As Exception
Response.Write(ex.ToString & "<hr /><br />")
ErrorLabel.Text = ex.Message
ErrorLabel.Visible = True
End Try
Return PortalUsers
End Function
Private Sub BindGrid(ByVal DataSource As Object)
With UsersGridView
.DataSource = DataSource
.DataBind()
End With
End Sub
End Class
Could someone at least help me understand what the LDAP url and login process is for this LDAP server?
Thanks
Last edited by JuggaloBrotha; May 20th, 2012 at 07:02 PM.
-
Jun 21st, 2011, 08:19 PM
#2
Re: Need to understand this, PHP connecting to LDAP
I've moved this from the PHP section because I think your problem is more to do with implementing the .NET code than working out the PHP script.
-
Jun 22nd, 2011, 09:01 AM
#3
Re: Need to understand this, PHP connecting to LDAP
Either or is fine, my problem is simply understanding how PHP is connecting to the LDAP so I can understand how to do it in .Net, which is why I posted it in the PHP subforum in the first place.
-
Jun 24th, 2011, 02:47 AM
#4
Re: Need to understand this, PHP connecting to LDAP
I take it you are running this application under IIS? If so, what user is running the application pool that you are testing with? Does this user have access to the LDAP server?
Gary
-
Jun 24th, 2011, 12:54 PM
#5
Re: Need to understand this, PHP connecting to LDAP
 Originally Posted by gep13
I take it you are running this application under IIS? If so, what user is running the application pool that you are testing with? Does this user have access to the LDAP server?
Gary
IIS isn't running on my computer, yet I can still run asp.net apps from VS & I have no idea what user it's under, probably the default.
Though I have no idea what user PHP on the dev server runs under either, but I'm inclined to think the account it's running under on windows shouldn't matter since the login credentials to the LDAP is being specified in the PHP code, I just don't understand how it's connecting and seems to work.
-
Jun 24th, 2011, 02:55 PM
#6
Re: Need to understand this, PHP connecting to LDAP
Hello,
That would mean that the application is running under your account. Does your user has access to LDAP?
Gary
-
May 17th, 2012, 10:28 PM
#7
Re: Need to understand this, PHP connecting to LDAP
I never did get this working, I was able to modify the php page into a couple of pages that do mostly what I want, though the user account that the php stuff uses doesn't have insert, update & delete permissions so it's all useless lol.
-
May 20th, 2012, 08:13 AM
#8
Re: Need to understand this, PHP connecting to LDAP
Hello,
From what I can see, this is very much a permission related problem. Did you confirm that your user, which is running the ASP.Net Application from within Visual Studio, has access to the LDAP Server?
Gary
-
May 20th, 2012, 10:23 AM
#9
Re: Need to understand this, PHP connecting to LDAP
 Originally Posted by gep13
Hello,
From what I can see, this is very much a permission related problem. Did you confirm that your user, which is running the ASP.Net Application from within Visual Studio, has access to the LDAP Server?
Gary
I took a look at the IBM Ldap on the server and there's only 1 account set up, which is the cn=root one, it's the admin account. I also took a look at the java websphere 5 portal application (which does the inserts, updates and deletes) and that's the same account it's using, so why it works for the java websphere app, but doesn't for the php (the php one does the selects just fine just not inserts, updates, and deletes) and .Net wont even connect to do a select.
Sometime today I'll post the php code I have now that tries to do an insert.
-
May 20th, 2012, 12:56 PM
#10
Re: Need to understand this, PHP connecting to LDAP
To you have those account credentials? i.e. can you run Visual Studio using those credentials?
Gary
-
May 20th, 2012, 01:15 PM
#11
Re: Need to understand this, PHP connecting to LDAP
I have always had problems using ldap and ad - but then started using PrincipalContext that is part of the DirectoryServices.AccountManagement namespace and I've had a lot more luck.
Not sure if that is anything close to what you are doing...
Code looks something like this.
Code:
Imports System.DirectoryServices.AccountManagement
.
.
.
Dim UserValid As Boolean = False
Dim pcDomain = System.Web.Configuration.WebConfigurationManager.AppSettings("addomain")
Dim pcContainer = System.Web.Configuration.WebConfigurationManager.AppSettings("adcontainer")
Dim pcUN = System.Web.Configuration.WebConfigurationManager.AppSettings("adun")
Dim pcPW = System.Web.Configuration.WebConfigurationManager.AppSettings("adpw")
If pcDomain = "spserver" And pcUN = "szlamany" Then
If ctrlval1 = ctrlval2 Then UserValid = True
End If
If pcDomain = "xyzweb01" Then
If ctrlval1.ToLower() = "testuser" And ctrlval2 = "demo" Then UserValid = True
End If
If Not UserValid Then
Dim domainContext As PrincipalContext
If pcUN = "" Then
domainContext = New PrincipalContext(ContextType.Domain, pcDomain, pcContainer)
Else
domainContext = New PrincipalContext(ContextType.Domain, pcDomain, pcContainer, pcUN, pcPW)
End If
If domainContext.ValidateCredentials(ctrlval1, ctrlval2) Then UserValid = True
End If
If UserValid Then
strMessage = nGuid.ToString
Else
strSuccess = ""
strMessage = "<br />Log in failure!"
End If
web.config stuff looks like this
Code:
<add key="addomain" value="spserver"/>
<add key="adcontainer" value="DC=antares; DC=local"/>
<add key="adun" value="szlamany"/>
<add key="adpw" value="asdrfasdf"/>
-
May 20th, 2012, 07:12 PM
#12
Re: Need to understand this, PHP connecting to LDAP
Here's the php webpage I've created that I would like to have insert the new ldap records:
Code:
<html><title>New LDAP Account</title><head>
<style type="text/css">
body
{font-family: helvetica, verdana, arial;font-size: 12px;color: #000;}
tr th
{font-family: helvetica, verdana, arial;font-size: 12px;border: solid 1px #000;background-color: #C0C0C0;}
tr td
{font-family: helvetica, verdana, arial;font-size: 12px;color: #000;border: solid 1px #000;}
.ErrorMsg
{background-color: #ff5050;border: solid 2px red;color: #ffffff;font-family: Verdana, Arial, Sans-Serif;font-weight: bold;padding: 3px 2px 3px 2px;width: 100%; margin: 5px 2px 5px 2px;}
.SuccessMsg
{background-color: #ADFF2F;border: solid 2px green;color: #ffffff;font-family: Verdana, Arial, Sans-Serif;font-weight: bold;padding: 3px 2px 3px 2px;width: 100%; margin: 5px 2px 5px 2px;}
</style>
</head>
<?php
if (isset($_POST["SaveButton"])) {
//Save the user to the LDAP
$ldaprdn = 'cn=root'; // ldap rdn or dn
$ldappass = 'password'; // associated password
$ldapconn = ldap_connect("server") or die("Could not connect to LDAP server.");
$result=false;
if ($ldapconn) {
//set up our entry array
$contact = array();
$contact['uid'] = trim($_POST["UIDTextBox"]);
$contact['objectclass'][0] = "inetorgperson";
$contact['objectclass'][1] = "top";
$contact['objectclass'][2] = "person";
$contact['objectclass'][3] = "organizationalPerson";
$contact['userpassword'] = $_POST["PasswordTextBox"];
$contact['givenname'] = trim($_POST["FirstNameTextBox"]);
$contact['sn'] = trim($_POST["LastNameTextBox"]);
$contact['cn'] = trim($_POST["FirstNameTextBox"])." ".trim($_POST["LastNameTextBox"]);
$contact['employeetype'] = $_POST["TypeDropDownList"];
// add user to ldap server
$base_dn = "cn=users,dc=ecop,dc=com";
$dn = 'cn='. $contact['cn'] .','. $base_dn;
$result = ldap_add($ldapconn, $dn, $contact);
if ($result) {
RenderPage("Success", false);
} else {
RenderPage("Could not create new contact", false);
}
}
} else {
RenderPage("", false);
}
function RenderPage($ErrorMessage, $CloseWindow)
{
$UID = "";
$Password = "";
$FName = "";
$LName = "";
$SelType = "Supplier";
if (isset($_POST["SaveButton"])) {
$UID = $_POST["UIDTextBox"];
$Password = $_POST["PasswordTextBox"];
$FName = $_POST["FirstNameTextBox"];
$LName = $_POST["LastNameTextBox"];
$SelType = $_POST["TypeDropDownList"];
}
echo "<body";
if ($CloseWindow) { echo " onload='Javascript:self.close();'"; }
echo "><form id='NewForm' name='NewForm' method='post'><center>\n";
if ($ErrorMessage != "") {
echo "<span class='";
if ($CloseWindow) {
echo "SuccessMsg";
} else {
echo "ErrorMsg";
}
echo "'>".$ErrorMessage."</span><br /><br />\n";
}
echo "<table border='0' cellspacing='0' cellpadding='5'>\n<tr><th colspan='2'>Enter LDAP Info</th></tr>";
echo "<tr><td>UID:</td><td><input type='text' name='UIDTextBox' id='UIDTextBox' value='".$UID."' /></td></tr>";
echo "<tr><td>Password:</td><td><input type='text' name='PasswordTextBox' id='LastNameTextBox' value='".$Password."' /></td></tr>";
echo "<tr><td>First Name:</td><td><input type='text' name='FirstNameTextBox' id='FirstNameTextBox' value='".$FName."' /></td></tr>";
echo "<tr><td>Last Name:</td><td><input type='text' name='LastNameTextBox' id='LastNameTextBox' value='".$LName."' /></td></tr>";
echo "<tr><td>Type:</td><td><select name='TypeDropDownList' id='TypeDropDownList'>";
echo "<option value='Buyer'";
if ($SelType == "Buyer") { echo " selected"; }
echo ">Buyer</option>";
echo "<option value='Planner'";
if ($SelType == "Planner") { echo " selected"; }
echo ">Planner</option>";
echo "<option value='Supplier'";
if ($SelType == "Supplier" || $SelType == "") { echo " selected"; }
echo ">Supplier</option>";
echo "</select>\n</table><br>";
echo "<input type='submit' id='SaveButton' name='SaveButton' value='Save' /> \n";
echo "<input type='button' id='CancelButton' name='CancelButton' value='Cancel' onclick='javascript:self.close();' />\n";
echo "</center></form>";
}
?>
</body></html>
and I'm getting a permissions error, yet it's the same un and password the websphere app uses to create new ldap entries.
Here's a screenshot of the ldap configuration:

 Originally Posted by gep13
To you have those account credentials? i.e. can you run Visual Studio using those credentials?
Gary
What do you mean "run VS with those credentials" ?
 Originally Posted by szlamany
I have always had problems using ldap and ad - but then started using PrincipalContext that is part of the DirectoryServices.AccountManagement namespace and I've had a lot more luck.
Not sure if that is anything close to what you are doing...
Code looks something like this.
Code:
Imports System.DirectoryServices.AccountManagement
.
.
.
Dim UserValid As Boolean = False
Dim pcDomain = System.Web.Configuration.WebConfigurationManager.AppSettings("addomain")
Dim pcContainer = System.Web.Configuration.WebConfigurationManager.AppSettings("adcontainer")
Dim pcUN = System.Web.Configuration.WebConfigurationManager.AppSettings("adun")
Dim pcPW = System.Web.Configuration.WebConfigurationManager.AppSettings("adpw")
If pcDomain = "spserver" And pcUN = "szlamany" Then
If ctrlval1 = ctrlval2 Then UserValid = True
End If
If pcDomain = "xyzweb01" Then
If ctrlval1.ToLower() = "testuser" And ctrlval2 = "demo" Then UserValid = True
End If
If Not UserValid Then
Dim domainContext As PrincipalContext
If pcUN = "" Then
domainContext = New PrincipalContext(ContextType.Domain, pcDomain, pcContainer)
Else
domainContext = New PrincipalContext(ContextType.Domain, pcDomain, pcContainer, pcUN, pcPW)
End If
If domainContext.ValidateCredentials(ctrlval1, ctrlval2) Then UserValid = True
End If
If UserValid Then
strMessage = nGuid.ToString
Else
strSuccess = ""
strMessage = "<br />Log in failure!"
End If
web.config stuff looks like this
Code:
<add key="addomain" value="spserver"/>
<add key="adcontainer" value="DC=antares; DC=local"/>
<add key="adun" value="szlamany"/>
<add key="adpw" value="asdrfasdf"/>
I'll have to give this a try
-
May 21st, 2012, 12:37 AM
#13
Re: Need to understand this, PHP connecting to LDAP
 Originally Posted by JuggaloBrotha
and I'm getting a permissions error, yet it's the same un and password the websphere app uses to create new ldap entries.
Although you are using the same credentials, I suspect that there is an issue with the identity of the process that is running Visual Studio, i.e. your account. For instance, do you know exactly what line the code is failing on? Are you even able to make the connection to the LDAP Server?
Gary
-
May 22nd, 2012, 02:14 PM
#14
Re: Need to understand this, PHP connecting to LDAP
 Originally Posted by gep13
Although you are using the same credentials, I suspect that there is an issue with the identity of the process that is running Visual Studio, i.e. your account. For instance, do you know exactly what line the code is failing on? Are you even able to make the connection to the LDAP Server?
Gary
I'm not sure what identity of the process is, here's the php code I have that does pull records out of the LDAP:
Code:
<?php
$UID = $_GET['UID'];
$isPostBack = false;
$boolEditClicked = isset($_POST["EditButton"]);
$boolSaveClicked = isset($_POST["SaveButton"]);
$boolCancelClicked = isset($_POST["CancelButton"]);
$isPostBack = ($boolEditClicked || $boolSaveClicked || $boolCancelClicked);
echo "<html><title>LDAP Details: ".$UID."</title><head>";
?>
<style type="text/css">
body
{font-family: helvetica, verdana, arial;font-size: 12px;color: #000;}
tr th
{font-family: helvetica, verdana, arial;font-size: 12px;border: solid 1px #000;background-color: #C0C0C0;}
tr td
{font-family: helvetica, verdana, arial;font-size: 12px;color: #000;border: solid 1px #000;}
</style>
<script language="javascript" type="text/javascript">
function SubmitForm()
{
var xForm = window.document.DetailsForm;
xForm.method="post";
xForm.submit();
}
</script>
</head><body><form id="DetailsForm" name="DetailsForm"><center>
<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection
// using ldap bind
$ldaprdn = 'cn=root'; // ldap rdn or dn
$ldappass = 'password'; // associated password
// connect to ldap server
$ldapconn = ldap_connect("server") or die("Could not connect to LDAP server.");
if ($ldapconn) {
if ($boolSaveClicked) {
//Updating the current LDAP entry, the save button was clicked
$dnToEdit = "cn=users,dc=ecop,dc=com"."";
$result = ldap_search($ldapconn, $dnToEdit);
if ($result) {
//Not finished yet
}
} else {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
// verify binding
if ($ldapbind) {
$srchString = "uid=".$UID;
//Search surname entry
$sr=ldap_search($ldapconn, "cn=users,dc=ecop,dc=com", $srchString);
$info = ldap_get_entries($ldapconn, $sr);
echo "<table border='1' cellspacing='0' cellpadding='5'><tr><th>LDAP Info</th><th>Factories</th></tr><tr><td><table border='0' cellspacing='0' cellpadding='5'>";
for ($i = 0; $i<$info["count"]; $i++) {
$strUid = "";
$strPW = "";
$strEmployeeType = "";
$strSn = "";
$strGivenName = "";
$strMail = "";
$strLanguage = "";
$strCN = "";
$intSupplierCount = 0;
for ($ii=0; $ii<$info[$i]["count"]; $ii++) {
$data = $info[$i][$ii];
for ($iii=0; $iii<$info[$i][$data]["count"]; $iii++) {
if ($data == "uid") {
$strUid = $info[$i][$data][$iii];
} else if ($data == "userpassword") {
$strPW = $info[$i][$data][$iii];
} else if ($data == "employeetype") {
$strEmployeeType = $info[$i][$data][$iii];
} else if ($data == "sn") {
$strSn = $info[$i][$data][$iii];
} else if ($data == "givenname") {
$strGivenName = $info[$i][$data][$iii];
} else if ($data == "mail") {
$strMail = $info[$i][$data][$iii];
} else if ($data == "preferredlanguage") {
$strLanguage = $info[$i][$data][$iii];
} else if ($data == "cn") {
$strCN = $info[$i][$data][$iii];
}
}
}
if ($strUid != "") {
echo "<tr><td>UID:</td><td>" . $strUid . "</td><td>CN:</td><td>";
if ($strCN != "") {
echo $strCN;
} else {
echo " ";
}
echo "</td></tr>";
if (!$boolEditClicked) {
//Display the results, not in edit mode
echo "<tr><td>Password:</td><td colspan='3'>" . $strPW . "</td></tr>";
echo "<tr><td>First Name:</td><td>" . $strGivenName . "</td><td>Last Name:</td><td>" . $strSn . "</td></tr>";
echo "<tr><td>Type:</td><td>";
if ($strEmployeeType != "") {
echo $strEmployeeType;
} else {
echo " ";
}
echo "</td><td>Language:</td><td>";
if ($strLanguage != "") {
echo $strLanguage;
} else {
echo " ";
}
echo "</td></tr>";
echo "<tr><td>Email:</td><td colspan='3'>";
if ($strMail != "") {
echo $strMail;
} else {
echo " ";
}
echo "</td></tr>";
} else {
//Edit the record
echo "<tr><td>Password:</td><td colspan='3'><input type='text' id='PasswordTextBox' name='PasswordTextBox' value='" . $strPW . "' style='width:100%;' /></td></tr>";
echo "<tr><td>First Name:</td><td><input type='text' id='FirstNameTextBox' name='FirstNameTextBox' value='" . $strGivenName . "' style='width:100%;' /></td><td>Last Name:</td><td><input type='text' id='LastNameTextBox' name='LastNameTextBox' value='" . $strSn . "' style='width:100%;' /></td></tr>";
echo "<tr><td>Type:</td><td><select id='TypeDropDownList' name='TypeDropDownList'><option value='Buyer'";
if ($strEmployeeType == "Buyer") {
echo " selected";
}
echo ">Buyer</option><option value='Planner'";
if ($strEmployeeType == "Planner") {
echo " selected";
}
echo ">Planner</option><option value='Supplier'";
if ($strEmployeeType == "Supplier") {
echo " selected";
}
echo ">Supplier</option></select></td>";
echo "<td>Language:</td><td><input type='text' id='LanguageTextBox' name='LanguageTextBox' value='" . $strLanguage . "' style='width:100%;' /></td></tr>";
echo "<tr><td>Email:</td><td colspan='3'><input type='text' id='EmailTextBox' name='EmailTextBox' value='" . $strMail . "' style='width:100%;' /></td></tr>";
}
}
}
echo "</table></td><td><ul>";
for ($i = 0; $i<$info["count"]; $i++) {
for ($ii=0; $ii<$info[$i]["count"]; $ii++) {
$data = $info[$i][$ii];
if ($data == "ecopsupplier") {
for ($jj=0; $jj<count($info[$i][$data])-1; $jj++) {
echo "<li>".$info[$i][$data][$jj]."</li>";
}
}
}
}
ldap_close($ldapconn);
echo "</ul></td></tr></table><br />\n";
if (!$boolEditClicked) {
echo "<input type='submit' id='EditButton' name='EditButton' value='Edit' onclick='Javascript:SubmitForm();' />";
} else {
echo "<input type='submit' id='SaveButton' name='SaveButton' value='Save' onclick='Javascript:SubmitForm();' /> ";
echo "<input type='submit' id='CancelButton' name='CancelButton' value='Cancel' onclick='Javascript:SubmitForm();' />";
}
} else {
die ("LDAP bind failed");
}
}
}
echo "<br /><br /><br /><input type='button' name='CloseButton' id='CloseButton' value='Close' onclick='Javascript:self.close();' /></form></center></body></html>";
?>
With that code I'm able to view the LDAP entry (I can even view it in "edit" mode with the textboxes and all), so I'm not sure why the insert doesn't work (insert page's code posted a couple of days ago).
Last edited by JuggaloBrotha; May 22nd, 2012 at 02:19 PM.
-
May 24th, 2012, 03:12 AM
#15
New Member
Re: Need to understand this, PHP connecting to LDAP
What's your previous PHP compatible with LDAP server?
-
Sep 2nd, 2012, 12:00 AM
#16
Re: Need to understand this, PHP connecting to LDAP
 Originally Posted by teguhyuliantos
What's your previous PHP compatible with LDAP server?
No clue, I can't get the PHP code to do an LDAP insert or update either so I'm at a loss.
A co-worker mentioned that .Net may not be able to connect to the LDAP if it doesn't have a .Net driver installed, but I don't have a clue how to check for either of these (PHP not doing updates and .Net not being able to connect at all)
The website is due to be sunsetted in 8 months, so there's no point in trying to get it to work now. Thanks for all of the suggestions guys.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|