vb.net authorization error with AD and LDAP - asp.net

We are upgrading our servers and .net application from windows 2000 to the newly-purchased windows 2012R2 servers. There is one function which works in windows 2000 but doesn’t work in windows 2012R2.
We are running an .net 2.0 internal application in windows 2000 and IIS 5.0 using Visual Studio professional 2015. There is one function in this application which will make a function call to an AD server using LDAP to check the login id and password in Active Directory. It is running perfectly fine before. However, once I upgrade to this new window2012R2 server running .net 2.0, it doesn’t work. The function in the application is not able to get authorization in the Active Directory. The function as below:
Private Function IsAuthenticatedByAD(ByVal sUid As String, ByVal sPwd As String) As Boolean
Dim direntRoot As DirectoryEntry, direntUsr As DirectoryEntry
Dim sDomain As String, sDomainAndUid As String
Dim dirsrchUsr As DirectorySearcher, oNative As Object
direntRoot = New DirectoryEntry("LDAP://rootDSE")
sDomain = direntRoot.Properties("DefaultNamingContext")(0)
sDomainAndUid = String.Format("{0}\{1}", sDomain, sUid)
direntUsr = New DirectoryEntry(direntRoot.Path, sDomainAndUid, sPwd)
Try
oNative = direntUsr.NativeObject
Catch ex As Exception
Return False
End Try
Return True
End Function
I received error message in the "Try" section when run oNative = ....
The error message as below:
"System.DirectoryServices.DirectoryServicesCOMException (0x8007052E):
The user name or password is incorrect." & vbCrLf & vbCrLf & " at
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)" &
vbCrLf & " at System.DirectoryServices.DirectoryEntry.Bind()" &
vbCrLf & " at
System.DirectoryServices.DirectoryEntry.get_NativeObject()" & vbCrLf &
" at ums.business.UsrMgmtBus.IsAuthenticatedByAD(String sUid, String
sPwd) in C:\inetpub\wwwroot\ums\business\UsrMgmtBus.vb:line 127"
Please help. Thanks a lot.

Related

ASP.NET VB Code Behind - Error The server response was: 5.7.1 Client was not authenticated

I have some ASP.NET code that I need to send an email this is the procedure I have cribbed on how to do that and it tries to send the email but after a fairly long pause comes up with this full error message:
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated."
I have poured over a lot of similar errors on this site and applied some of the fixes that should allow my code to send email and none work.
My ASP.NET code is running on a 2012 r2 Server that is on the same internal network as the mail server which is running Server 2008 r2 and Exchange Server 2013.
The ASP.NET server can be accessed via "remote.domainname.co.uk" and the Mail Server can be accessed via "mail.dommainname.co.uk" where domainname is a placeholder for the actual domain name.
This is the code that I am using:
Dim mailto As New MailAddress("toaddress#mydomain.com") 'My developer email add for testing.
Dim mailfrom As New MailAddress("fromaddress#domainname.co.uk")
Dim message As New MailMessage(mailfrom, mailto), Msg As String = ""
Dim mailClient As New SmtpClient()
Dim UserAndPass As New NetworkCredential()
Dim Script = ""
Dim n As Integer = 0
Dim BodyText As String = ""
Try
message.Subject = "Issue relating to " & p.IssueDescription & "."
'Create the body text:
BodyText = "This email is to bring to your attention the following issue:" & NNL
BodyText += "Building: " & p.Building & NL
BodyText += "Location: " & p.Location & NL
BodyText += "Issue:" & p.IssueDescription & NL
BodyText += "Additional Information:" & NNL
BodyText += p.AdditionalInfo & NNL
BodyText += "Sent from the XYZ Logging System." & NL
BodyText += "Date: " & Now.ToShortDateString & NL
BodyText += "Time: " & Now.ToShortTimeString
message.Body = BodyText
'send the message
mailClient = New SmtpClient("mail.domainname.co.uk", 25)
mailClient.EnableSsl = True
mailClient.UseDefaultCredentials = False
mailClient.Credentials = New Net.NetworkCredential("fromaddress#domainname.co.uk", "passwordtext")
mailClient.Send(message)
Script = "alert('"
Script += "The Patrols Issue Email has been successfully sent!"
Script += "')};"
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", Script, True)
Catch ex As Exception
PEH("SendEmail", "frmName", ex.Message) 'My error handler
Finally
'f.Dispose()
mailClient.Dispose()
message.Dispose()
End Try
On the Exchange server I have the standard set of receive connectors and I have checked that they are all configured as per the standard install and they are. I did try creating my own receive connector but this caused problems with emails being sent from remote senders getting bounced with the same "Client was not authenticated" error so I removed it again.
Any help with this would be appreciated.
Graham Sivill.

Google Drive authentication in VB.NET to download a file

My goal is to download a file from Google Drive using the Drive API v3 and VB.NET.
I set up my credentials in the Google console: Under "OAuth 2.0 client IDs" I put "http://localhost" in "Authorized redirect URIs" and in "Authorized JavaScript origins" and have my client secret file. I am on ASP.NET 4.0 using NuGet package Google.Apis.Drive.v3.
The error happens on line "credential = GoogleWebAuthorizationBroker.AuthorizeAsync". It pops up a new Chrome tab and says:
That’s an error.
Error: redirect_uri_mismatch
The redirect URI in the request, http://localhost:9895/authorize/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/[MyClientID]?project=[MyProjectNumber]
However each time I get a different port number.
Public Function AuthenticateOauth() As DriveService
' Request authentication from a user using oAuth2
Dim clientSecretJson = "C:\WebApps\PeruvianGuineaPig\App_Data\client_secret.json"
Dim applicationName = "DriveApi"
Try
' Permissions
Dim scopes As String() = New String() {DriveService.Scope.DriveReadonly}
Dim credential As UserCredential
Using stream As New FileStream(clientSecretJson, FileMode.Open, FileAccess.Read)
Dim credPath As String
credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly.GetName.Name)
' Requesting Authentication
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
"user",
CancellationToken.None,
New FileDataStore(credPath, True)).Result
End Using
' Create Drive API service
Dim Service = New DriveService(New BaseClientService.Initializer() With
{.HttpClientInitializer = credential, .ApplicationName = applicationName})
Return Service
Catch ex As Exception
Return Nothing
End Try
End Function
I didn't realize I needed to open the project as a Web Site (and pick it from my list of Local IIS Sites) and not simply open the Project/Solution file. It now uses the port number I gave it in IIS when I'm debugging.
I have another issue now, but that's for another question...

How do I get my old VBScript ASP sendemail to work on Azure?

I recently migrated my ASP.Net website from a traditional windows 2003 shared server to Azure as a Web App. My VBScript forms which send e-mails to me have stopped working since the migration. I have tried a few different approaches to get my VBScript email code to work but have had no luck so far. Part of the problem is that I can't see what the error is.
The first part of my question is: How do I make the ASP.Net errors on my VBScript ASP page visible? I have set debug='true' in my web.config and I tried to set it on my ASP page (see below) but this hasn't worked. Currently I just get an 'Internal error 500' page after attempting to send the email with no indication of what went wrong.
Here is the code that sends the e-mail and appears to be the source of the problem. Can do I change this to work under Azure without rewriting my entire page in C#?
<%# Language=VBScript Debug='true' %> 'Debug=true doesn't work
Set Mailer = Server.CreateObject("Persits.MailSender")
Mailer.Host = "mail.mydomain.com" ' Specify a valid SMTP server
Mailer.From = Request.Form("AgentEmail") ' Specify sender's address
Mailer.FromName = Request.Form("AgentsName") ' Specify sender's name
Mailer.Port = 587
Mailer.isHTML = True
Mailer.AddAddress "person1#email.com"
Mailer.AddAddress "person2#email.net"
Mailer.AddAddress "person3#email.com"
Mailer.AddAddress Request.Form("AgentEmail")
Mailer.Body = "stuff in my email"
Mailer.Username = "me#emailcom"
Mailer.Password = "123456"
On Error Resume Next
Mailer.Send
If Err <> 0 Then
Response.Write "Error encountered: " & Err.Description
Else
Response.Write "Success"
End If
This code did work on my old Windows server. I've left out all of the HTML since that part appears to work just fine.
Assuming you're using Azure Websites (and not an Azure VM), you can use Classic ASP provided you jump through some hoops: https://khailiangtech.wordpress.com/2011/06/03/windows-azure-how-to-enable-classic-asp-support/
Windows Azure seems to support CDO (the built-in COM SMTP service) whereas your code is using Persits.MailSender - it might be possible to install the Persits.MailSender component via the <ServiceDefinition> XML - but I don't recommend this because of the 32/64-bit problem.
I suggest changing your script to use CDO instead, here's a reference: http://theholmesoffice.com/using-sendgrid-with-classic-asp-to-send-emails/ (the page is for using SendGrid's SMTP server, but you can use any SMTP server (just don't use port 25).
You're trying to instantiate an object from a DLL that is not installed: Server.CreateObject("Persits.MailSender")
You can't install any external COM object when using Web Apps. One option is to use a Virtual Machine and install your COM DLL.
For future reference, I ended up solving my problem by converting my code to C# and using to smtpClient. This is the general idea here:
SmtpClient smtpClient = new SmtpClient("mail.domain.com", 587);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(From, "password");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Port = 587;
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(From, "Me");
smtpClient.Host = "mail.domain.com";
message.From = fromAddress;
message.To.Add(To);
message.Subject = Subject;
message.IsBodyHtml = true;
message.Body = Body;
smtpClient.Send(message);
Label_Results.Text = "Email successfully sent.";
}
catch (Exception ex)
{
ErrorLabel.Text = "<p>Send Email Failed:<p>" + ex.Message;
}

Reverse DNS lookup to https over vpn not resolving

I'm performing a reverse DNS lookup to determine whether the user is on an appropriate domain in order to tailor the experience to their specific requirements and the code below is working correctly, except under the following specific instance.
when connecting to the site over a VPN and via https:// (vpn and http:// work as intended) The following error is thrown: "Error: The requested name is valid, but no data of the requested type was found."
Upon closer investigation the system is returning an odd computer name (eg: 3EDs45F46FG) and not the expected reverse lookup (eg: ws234.domainName.com)
Public Shared Function GetDomain() As String
Dim RQST As System.Web.HttpRequest
RQST = HttpContext.Current.Request
Return ReverseLookup(RQST.UserHostName)'UserHostName as ip address
End Function
Public Shared Function ReverseLookup(ip As String) As String
Dim netDns As System.Net.Dns
Try
Dim host As New IPHostEntry
host = netDns.GetHostEntry(ip)
Return host.HostName & "<BR><BR>ip: " & ip
Catch ex As System.Net.Sockets.SocketException
Return "Error: " & ex.Message & "<BR><BR>" & "ip: " & ip
End Try
End Function

Classic ASP : Capture Errors

Is it possible to capture all 500 errors in Classic ASP at a global level? Maybe something in IIS. I'm using II6 at the moment. I like to capture the error message and then store it in the database. I know its possible in ASPX pages, but don't know exactly how you do in classic asp.
Thank you
Yes, create an asp page which will log the error details to the database, and set this to be the 500 handler page in IIS as below.
Use the Server.GetLastError object to get the details of the error in your handler script.
It might be a good idea to log to a text file rather than a DB in your 500 handler for resiliency.
Complementing Jon's answer, use this script to write errors to a log file:
<%
'Set this page up in IIS to receive HTTP 500 errors
''Type' needs to be 'URL' and the URL is e.g.: '/500Error.asp' if this file is named '500Error.asp' and is in the site root directory.
'This script assumes there is a "/Log" folder, and that IIS has write access to it.
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim objFSO, err
Set objFSO=CreateObject("Scripting.FileSystemObject")
Set err = Server.GetLastError()
outFile=Server.MapPath("/Log/ErrorLog.txt")
Set objFile = objFSO.OpenTextFile(outFile, ForAppending, True, TristateTrue)
objFile.WriteLine Now & " - ERROR - ASPCode:" & err.ASPCode & " ASPDescription: " & err.ASPDescription & " Category: " & err.Category & " Description: " & err.Description & " File: " & err.File & " Line: " & err.Line & " Source: " & err.Source & vbCrLf
objFile.Close
Set objFile = Nothing
Set err = Nothing
%>
Error handling in classic ASP is a complete pain. You can catch the error where you think it's going to occur using on error resume next, then check for the error code in the following line of code.
Alternately you can scan the server logs for 500 errors. or set up a "500 error" page in your IIS settings.
On Error Resume Next
... do something...
If Err.Number <> 0 Then
... handle error
end if
To add to #Jon Eastwood's answer - if you are using IIS 7.5, then instead of "Custom errors" you will look for ".NET Error Pages" per the image below:
This applies to Windows Server 2008 and other newer Windows SKUs.

Resources