MS Access 2010 using ldap authentication - ldap

I am trying to do ldap authentication in ms access 2010 using username and password. I cannot seem to figure this out and have tried different codes online but none seem to work. Can anyone help?
The following is what i have taken from here
Function CheckUser(username As String, passwd As String, Level As Integer) As Boolean
On Error GoTo LDAP_Error
username = "sharifu"
passwd = "xxx"
Const ADS_SCOPE_SUBTREE = 2
Dim LDAPPath As String
LDAPPath = "LDAP://172.16.0.12/OU=Sites;DC=domain;DC=com"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "domain\" & username
conn.Properties("Password") = "" & passwd
conn.Properties("Encrypt Password") = True
'conn.Properties("ADSI Flag") = 3
conn.Open "Active Directory Provider"
Set cmd.ActiveConnection = conn
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
cmd.CommandText = _
"SELECT Name FROM '" & LDAPPath & "' WHERE " & "objectCategory='user'"
Set rs = cmd.Execute
rs.Close
conn.Close
CheckUser = True
Exit Function
LDAP_Error:
If Err.Number = -2147217911 Then
MsgBox "Incorrect PeopleSoftID or Password!", vbExclamation, "HILDA"
Else
MsgBox "Error : " & Err.Description & " " & Err.Number, vbExclamation, "HILDA"
End If
CheckUser = False
conn.Close
End Function
Error I receive is
"Error: The server is not operational.
-2147217865"
Changed to ip address get following error now
Method 'ActiveConnection' of object '_Command' failed but it might be coming from elsewhere in my code. how would i check if ldap was success?

I have fixed issue.
Function CheckUser(UserName As String, passwd As String, Level As Integer) As Boolean
On Error GoTo LDAP_Error
Const ADS_SCOPE_SUBTREE = 2
Dim LDAPPath As String
LDAPPath = "LDAP://akutan.country.domain.com/OU=Sites;DC=domain;DC=com"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "xxx\" & UserName
conn.Properties("Password") = "" & passwd
conn.Properties("Encrypt Password") = True
'conn.Properties("ADSI Flag") = 3
conn.Open "Active Directory Provider"
Set cmd.ActiveConnection = conn
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
cmd.CommandText = "SELECT Name FROM '" & LDAPPath & "' WHERE " & "objectCategory='user'"
Set rs = cmd.Execute
rs.Close
conn.Close
CheckUser = True
[TempVars]![CurrentUser] = UserName
Call LogUser([TempVars]![CurrentUser], "Logon")
Exit Function
LDAP_Error:
If Err.Number = -2147217911 Then
MsgBox "Incorrect PeopleSoftID or Password!", vbExclamation, "LDAP Authentication"
Else
MsgBox "Error : " & Err.Description & " " & Err.Number, vbExclamation, "LDAP Authentication"
End If
CheckUser = False
conn.Close
End Function

Making little changes and explaining for understanding this code and a correct functioning:
Added the check if the user exist in the Database.
Changed "OU=Sites" in the LDAP path by "CN=Users".
LDAPPath = "LDAP://replace with IP or DNS name/CN=Users;DC=replace with domain name without .com;DC=replace with com, net or root node name"
In IP or DNS Name you must to specify the server IP or DNS Name.
In the first "DC" you must to specify the Domain Name without .com or .net would be like this "google".
In the second "DC" you must to specify the Domain type for intance "com", you can see this post if you want to know what means
Full example:
LDAPPath = "LDAP://200.201.1.1/CN=Users;DC=google;DC=com"
or
LDAPPath = "LDAP://ldap.google.com/CN=Users;DC=google;DC=com"
In this line: conn.Properties("User ID") = "replace with domain short name\" & userName
conn.Properties("User ID") = "ggle\" & userName
Finaly this the full code:
Function ldapAuth(userName As String, passwd As String, level As Integer) As Boolean
On Error GoTo LDAP_Error
ldapAuth = False
If Not IsNull(userName) And Not IsNull(passwd) Then
'Check if the user exist in DB
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim qdf As QueryDef
Dim strSQL As String
Set dbs = CurrentDb
strSelect = "SELECT *"
strFrom = " FROM employee"
strWhere = " WHERE user_name = '" & userName & "';"
strSQL = strSelect & strFrom & strWhere
Debug.Print strSQL
Set rst = dbs.OpenRecordset(strSQL, dbOpenDynaset)
'If the recordset is empty, exit.
If rst.EOF Then
MsgBox "The user not exist in the DataBase!!!"
Else
'Check user with LDAP
Const ADS_SCOPE_SUBTREE = 2
Dim LDAPPath As String
LDAPPath = "LDAP://ldap.google.com/CN=Users;DC=google;DC=com"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
Set cmd = New ADODB.Command
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "ggle\" & userName
conn.Properties("Password") = "" & passwd
conn.Properties("Encrypt Password") = True
'conn.Properties("ADSI Flag") = 3
conn.Open "Active Directory Provider"
Set cmd.ActiveConnection = conn
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
cmd.CommandText = "SELECT Name FROM '" & LDAPPath & "' WHERE " & "objectCategory='user'"
Set rs = cmd.Execute
rs.Close
conn.Close
'Set userId and Role Globally
employeeId = rst![id]
employeeType = rst![employee_type]
TempVars.Add "employeeId", employeeId
TempVars.Add "employeeType", employeeType
'Log user login and role
Debug.Print "User login: " & TempVars!employeeId
Debug.Print "User Role: " & TempVars!employeeType
ldapAuth = True
rst.Close
End If
End If
Exit Function
LDAP_Error:
If Err.Number = -2147217911 Then
'MsgBox "Incorrect User or Password!", vbExclamation, "LDAP Authentication"
Else
MsgBox "Error : " & Err.Description & " " & Err.Number, vbExclamation, "LDAP Authentication"
End If
conn.Close
End Function

Related

How to bypass sql connection error with simple msgbox

Preparing the connection check to the SQL sever, which gives me below error if not in our group network its obsoletely fine but simple msgbox sufficient for me
enter image description here
Sub ADOExcelSQLServer()
Dim Cn As ADODB.connection
Dim server_name As String
Dim database_name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Set rs = New ADODB.Recordset
Set ws = ActiveSheet
server_name = "192.168.x.xxx\SQLEXPRESS"
database_name = "ABC_System"
User_ID = "xx"
Password = "12345"
SQLStr = "SELECT * FROM dbo.Tbl_anb"
'SQLStr = "dbo.Tbl_wid"
Set Cn = New ADODB.connection
Cn.Open "Driver={SQL Server};Server=" & server_name & ";Database=" & database_name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
If Cn.State = 1 Then
Debug.Print "Connected!"
MsgBox "Connected"
Else
MsgBox "Not Connected"
End If
Here is modified version with On error:
Dim Cn As ADODB.connection
Dim server_name As String
Dim database_name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Set rs = New ADODB.Recordset
Set ws = ActiveSheet
server_name = "192.168.x.xxx\SQLEXPRESS"
database_name = "ABC_System"
User_ID = "xx"
Password = "12345"
SQLStr = "SELECT * FROM dbo.Tbl_anb"
'SQLStr = "dbo.Tbl_wid"
Set Cn = New ADODB.connection
On error resume next
Cn.Open "Driver={SQL Server};Server=" & server_name & ";Database=" & database_name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
on error Goto 0
If Cn.State = 1 Then
Debug.Print "Connected!"
MsgBox "Connected"
Else
MsgBox "Not Connected"
end if

How to solve the system error &H80040E14 (-2147217900) in excel ADOB connection

I am trying to get the data from a SQL database through excel, I am using a ADOB connection. It was working fine and now i get a run time error, do not know what is the cause of it. I have not changed a code. My following code is:
Public Sub SQL_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim StrQuery As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
With ActiveSheet()
.Unprotect Password:=*****
End With
Sheets(2).Range("A2:H2").ClearContents
........
If CheckBox4.Value = True Then
strCon = "Provider=SQLOLEDB;Data Source=******\SQLEXPRESS;" & _
"Initial Catalog=testdata;" & _
"User ID=test;Password=*****;"
End If
........
If CheckBox4.Value = True Then
Const DB_CONNECT_STRING = "Provider=SQLOLEDB;Data Source=******\SQLEXPRESS;Initial Catalog=testdata;user id ='test';password=*****"
Set myConn = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command")
myConn.ConnectionTimeout = 15
myConn.Open DB_CONNECT_STRING1
Set myCommand.ActiveConnection = myConn
myCommand.CommandText = "UPDATE Rewind SET Cause = '" & Sheets(2).Range("I2") & "' WHERE RewindID = '" & Sheets(2).Range("J2") & "'"
myCommand.Execute
myConn.Close
End If
With ActiveSheet
.Protect Password:=66090
End With
End Sub
Please help.

Select SQL Statement in Excel VBA

Sub LogCheck()
Dim cn As Object
Dim rs As Object
Dim StrSql As String
Dim strConnection As String
Dim AppPath As String
Set cn = CreateObject("ADODB.Connection")
AppPath = Application.ActiveWorkbook.Path
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\ceo.accdb;"
cn.Open strConnection
S_ID = Sheets("My").Range("A1").Value
StrSql = "SELECT * FROM EDO Where ID = ' " & S_ID & " '"
rs.Open StrSql, cn
If rs = Null Then
MsgBox "Record Not found"
Else
MsgBox "Record Found"
End If
End Sub
I am unable to run this code. Its showing error. Please help me out. Thanks!
Here S_ID is the data which I would like to search from table & ID is the primary key in the EDO Table.
In this case you may detect if the recordset is empty checking .EOF property:
Sub TestIfRecordFound()
Dim strConnection As String
Dim strID As String
Dim strQuery As String
Dim objConnection As Object
Dim objRecordSet As Object
strConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='C:\ceo.accdb';"
strID = Sheets("My").Range("A1").Value
strQuery = _
"SELECT * FROM EDO WHERE ID = '" & strID & "';"
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open strConnection
Set objRecordSet = objConnection.Execute(strQuery)
If objRecordSet.EOF Then
MsgBox "Record Not found"
Else
MsgBox "Record Found"
End If
objConnection.Close
End Sub
If Id is numeric than the sql should be:
StrSql = "SELECT * FROM EDO WHERE Id = " & S_ID
You also did not define S_ID, so it will be handle as a variant here. If you still get an error, you might have to make it "& CStr(S_ID)".

Connect to a SQL Server database with Outlook

I want to connect to a MS SQL Server database using an Outlook macro. But I don't know if the code is wrong or I need to add a library/driver or what happens here but it doesn't work.
Private Sub Application_Startup()
On Error GoTo ExitHere
'adodb connection to other database
stg_cn.Open "Provider = SQLOLEDB;" & _
"Data Source = 192.168.100.100;" & _
"Initial Catalog = hugeDB;" & _
"Integrated Security=SSPI;" & _
"User ID = oneuser;" & _
"Password = onepassword;"
sQuery = "SELECT * FROM documents where location = 'IE'"
'set reference to query
Set cmd = New ADODB.Command
cmd.ActiveConnection = stg_cn
cmd.CommandType = adCmdText
cmd.CommandText = sQuery
Set rs = cmd.Execute
Do While Not rs.EOF
For i = 0 To rs.Fields.count - 1
MsgBox (i + 1)
Next
rs.MoveNext
Loop
ExitHere:
If Not stg_cn Is Nothing Then stg_cn.Close
Set rs = Nothing
Set stg_cn = Nothing
Exit Sub
End Sub
On eye-test I am not able to figure out whats wrong, I think it has to do something with the way you are doing the ADO operations.
But I am just putting up the last macro I wrote to connect to SQL-Server from Macro. Hope it helps.
Private Sub Workbook_Open()
On Error GoTo ErrorHandler
'**************************************Initialize Variables**************************************
sServer = "<SQL SERVER Server>"
sDBName = "<SQL SERVER DB>"
'**************************************Open Connection**************************************
'adodb connection to other database
stg_cn.Open "Provider=SQLOLEDB;Data Source=" & sServer & _
";Initial Catalog=" & sDBName & _
";Integrated Security=SSPI;"
sQuery = "SELECT * " & _
"FROM Table "
'set reference to query
Set cmd = New ADODB.Command
cmd.ActiveConnection = stg_cn
cmd.CommandType = adCmdText
cmd.CommandText = sQuery
Set rs = cmd.Execute
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
<PERFORM OPERATIONS>
Next
rs.MoveNext
Loop
ExitHere:
If Not stg_cn Is Nothing Then stg_cn.Close
Set rs = Nothing
Set stg_cn = Nothing
Exit Sub
End Sub
The connection string #CodePhobia has provided should work for you.
The below just includes User ID and Password functionality, as your original question showed trying to connect using this.
Dim rsConn as ADODB.Connection
Set rsConn = New ADODB.Connection
With rsConn
.ConnectionString = "Provider = sqloledb;" & _
"Data Source = myServerName;" & _
"Initial Catalog = myCatalog;" & _
"Integrated Security=SSPI;" & _
"User ID = myUserID;" & _
"Password = myPassword;"
.Open
End With
You can use this website to find connection strings in the future. It should cover all possible connections you wish to establish.

User authentication over LDAP in asp

I want to pass username and password to LDAP and retrieve user information. I have code below but don't know where must I add password string in it?
strUsername = Request.Form("username")
strPassword = Request.Form("password")
Set rootDSE = GetObject("LDAP://RootDSE")
Set oConn = CreateObject("ADODB.Connection")
sDomainContainer = rootDSE.Get("defaultNamingContext")
Debug "DomainContainer: " & sDomainContainer
oConn.Properties("Encrypt Password") = true
oConn.Provider = "ADSDSOObject"
oConn.properties("user id") = sLdapReaderUsername
oConn.properties("password") = sLdapReaderPassword
oConn.Open "ADs Provider"
sQuery = "<LDAP://" & sDomainContainer & ">;(sAMAccountName=" & strUsername & ");adspath,mail,displayName;subtree"
Set userRS = oConn.Execute(sQuery)
If Not userRS.EOF and not err then
sFullName = userRS("displayName")
sEmail = userRS("mail")
sExternalID = ""
sOrganization = ""
Response.Write("sFullName: "&sFullName)
Response.Write("sEmail: "&sEmail)
.
..
...
This worked for me:
function AuthenticateUser(Username,Password,Domain)
dim strUser,strPass,strQuery,oConn,cmd,oRS
AuthenticateUser = false
strQuery = "SELECT cn FROM 'LDAP://" & Domain & "' WHERE objectClass='*'"
set oConn = server.CreateObject("ADODB.Connection")
oConn.Provider = "ADsDSOOBJECT"
oConn.properties("User ID") = Username
oConn.properties("Password")=Password
oConn.properties("Encrypt Password") = true
oConn.open "DS Query", Username,Password
set cmd = server.CreateObject("ADODB.Command")
set cmd.ActiveConnection = oConn
cmd.CommandText = strQuery
on error resume next
set oRS = cmd.Execute
if oRS.bof or oRS.eof then
AuthenticateUser = false
else
AuthenticateUser = true
end if
set oRS = nothing
set oConn = nothing
end function