Ldap query returns null result when deployed - asp.net

I'm using a very simple Ldap query in my asp.net mvc 2.0 site:
String ldapPath = ConfigReader.LdapPath;
String emailAddress = null;
try
{
DirectorySearcher search = new DirectorySearcher(ConfigReader.LdapPath);
search.Filter = String.Format("(&(objectClass=user)(objectCategory=person)(objectSid={0})) ", securityIdentifierValue);
// add the mail property to the list of props to retrieve
search.PropertiesToLoad.Add("mail");
var result = search.FindOne();
if (result == null)
{
throw new Exception("Ldap Query with filter:" + search.Filter.ToString() + " returned a null value (no match found)");
}
else
{
emailAddress = result.Properties["mail"][0].ToString();
}
}
catch (ArgumentOutOfRangeException aoorEx)
{
throw new Exception( "The query could not find an email for this user.");
}
catch (Exception ex)
{
//_log.Error(string.Format("======!!!!!! ERROR ERROR ERROR !!!!! in LdapLookupUtil.cs getEmailFromLdap Exception: {0}", ex));
throw ex;
}
return emailAddress;
It works fine on my localhost machine. It works fine when I run it in VS2010 on the server. It always returns a null result when deployed.
Here is my web.config:
Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<!--
-->
section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
-->
I'm running it under the default app pool.
Does anybody see the problem? This is driving me crazy!

OK, so I forgot to add that I have changed the user account running the Default App Pool to a user that has auth to run LDAP queryies.

Related

when I use asmx service and SSRS report service I am getting "The request failed with http status 401: unauthorised"

I was trying to call report related service (asmx) from my asp.net web application by running locally.
Then an exception happened saying. The request failed with http status401:unauthorised.
In my analysis I understood the issue caused due to below code
SSRSWebService.ReportingService2005 rs = new SSRSWebService.ReportingService2005();
rs.Credentials = new MyReportServerCredentials().NetworkCredentials;
and
Uri reportUri = new Uri(ConfigurationManager.AppSettings["ReportServerManagement.ReportingService2005"]);
this.rptViewer.ServerReport.ReportServerCredentials = new MyReportServerCredentials();
In my detailed analysis I understood that the issue was because of the credential set up in serviceObject.credential OR ServerReport.ReportServerCredentials was wrong. This can be rectified in two different way either by setting credential to default with below code
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;//"rs" is report object
Or locate below code and set up proper authenticated user credential in the code
public WindowsIdentity ImpersonationUser
{
get
{
// Use the default Windows user. Credentials will be
// provided by the NetworkCredentials property.
return null;
}
}
public ICredentials NetworkCredentials
{
get
{
// Read the user information from the Web.config file.
// By reading the information on demand instead of
// storing it, the credentials will not be stored in
// session, reducing the vulnerable surface area to the
// Web.config file, which can be secured with an ACL.
// User name
string userName =
<<AccurateUserName;>>
// Password
string password =
<<AccuratePassword;>>
// Domain
string domain = <<AccurateDomainName;>>
return new NetworkCredential(userName, password, domain);
}
}
In order to check whether which user has the access, we need to type service url ending with asmx (http:/MyServiceHostedServer/MyService.asmx) in a web browser. It will prompt a user name and password . Give our username as :Domain\Username and password.If we are able to see wsdl xml file then that user has the access.

Thread aborting issue with Sharp Svn with C#.Net 4.0

I have developed ASP.net application using VS-2010, C#.Net 4.0 with SharpSvn dll. When I'm working with dev server(don't have 3-Tier Architecture), it works fine. But when we are working with QA environment(have 3-Tier Architecture) it gives thread abort exception most of the time.Following shows the code and error log I have. Any help on this really appreciate.
public bool Checkout(string svnurl, string target)
{
try
{
using (_client = new SharpSvn.SvnClient())
{
_client.LoadConfiguration(Path.Combine(Path.GetTempPath(), "Svn"), true);
_client.Authentication.DefaultCredentials = new TNetworkCredential(_username, _password);
_client.Authentication.SslServerTrustHandlers += SvnSslOveride;
var targetsvn = new SvnUriTarget(svnurl);
if (_client.CheckOut(targetsvn, target))
{
Log.Info("Successfully checked out to following location : " );
Log.Info(target);
return true;
}
}
Log.Info("Unable to checkout "+ svnurl +" Svn location to target location : ");
Log.Info(target);
return false;
}
catch (Exception ee)
{
Log.Error("Error:SvnClient checkout....");
Log.Error(ee);
throw ee;
return false;
}
}
private static void SvnSslOveride(object sender, SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = true;
}
error log
ERROR 2013-08-12 12:13:37,714 3223821ms SvnClient Checkout -
Error:SvnClient checkout.... ERROR 2013-08-12 12:13:37,730 3223837ms
SvnClient Checkout - System.Threading.ThreadAbortException: Thread was
being aborted. at svn_client_checkout3(Int32* , SByte* , SByte* ,
svn_opt_revision_t* , svn_opt_revision_t* , svn_depth_t , Int32 ,
Int32 , svn_client_ctx_t* , apr_pool_t* ) at
SharpSvn.SvnClient.CheckOut(SvnUriTarget url, String path,
SvnCheckOutArgs args, SvnUpdateResult& result) at
SharpSvn.SvnClient.CheckOut(SvnUriTarget url, String path)
I missed <httpRuntime executionTimeout="(time in seconds)">
tag in web config and it automatically set by IIS server. The default is 110 seconds.
Note :In the .NET Framework 1.0 and 1.1, the default is 90 seconds.
After I added following line to web.config and it works fine.
<httpRuntime executionTimeout="600">
Previously it works sometimes because the time taken to SVN checkout in DEV server is less than in other environment because of the size of the repositories and network connections. Thanks all for your answers
As per my comment above, I've seen this issue. It appears to be related to plink authentication.
I resolved it by upgrading to the latest build of SharpSVN v1.7, at which point the error changed from a null-ref exception in the C++, to an SVN exception with the message "Can't create tunnel: The parameter is incorrect".
There are a few articles which explain how to resolve this, the best of which I've found here:
SVN+SSH and Sourceforge
In my case, changing the backslashes to forwardslashes in the SVN_SSH env var resolved the problem. Worth giving a shot.

Getting Forms Authentication from an ASP.NET logon page used by Silverlight 4 application

This is supposed to just work. I've read all the articles I could find via google on the topic, tried to copy as much as I could from other articles on both StackOverflow and CodeProject and others, but regardless of what I try - it doesn't work.
I have a silverlight application that runs fine using Windows Authentication.
To get it running under Forms Authentication I've:
Edited the web.config file to enable Forms Authentication (and delete the Windows Authentication configuration):
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="logon.aspx" defaultUrl="index.aspx" protection="All" path="/" timeout="30" />
</authentication>
Created a standard logon.aspx and logon.aspx.cs code behind page to take a user input name and password, and create a authentication cookie when the logon was successful, and then redirected the user to the root page of the web site, which is a silverlight application:
private void cmdLogin_ServerClick( object sender, System.EventArgs e )
{
if ( ValidateUser( txtUserName.Value, txtUserPass.Value ) )
{
FormsAuthentication.SetAuthCookie(txtUserName.Value, true);
var cookie = FormsAuthentication.GetAuthCookie(txtUserName.Value, true);
cookie.Domain = "mymachine.mydomain.com";
this.Response.AppendCookie(cookie);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if ( strRedirect == null )
strRedirect = "index.aspx";
Response.Redirect( strRedirect, true );
}
}
So the redirect after successfully logging in launches my silverlight application.
However the user is not authenticated when executing the Silverlight startup code:
public App()
{
InitializeComponent();
var webContext = new WebContext();
webContext.Authentication = new FormsAuthentication();
ApplicationLifetimeObjects.Add( webContext );
}
private void ApplicationStartup( object sender, StartupEventArgs e )
{
Resources.Add( "WebContext", WebContext.Current );
// This will automatically authenticate a user when using windows authentication
// or when the user chose "Keep me signed in" on a previous login attempt
WebContext.Current.Authentication.LoadUser(ApplicationUserLoaded, null);
// Show some UI to the user while LoadUser is in progress
InitializeRootVisual();
}
The error occurs in the ApplicationUserLoaded method, which always has its HasError property set to true on entry to the method.
private void ApplicationUserLoaded( LoadUserOperation operation )
{
if((operation != null) && operation.HasError)
{
operation.MarkErrorAsHandled();
HandlerShowWebServiceCallBackError(operation.Error, "Error loading user context.");
return;
}
...
}
The error reported is as follows - from what it appears to me is that the user isn't considered authenticated on entry to the silverlight app, so it is directing the code to try to return the logon page, which is returning data unexpected by the silverlight app:
An exception occurred while attempting to contact the web service.
Please try again, and if the error persists, contact your administrator.
Error details:
Error loading user context.
Exception details:
Load operation failed for query 'GetUser'. The remote server returned an error: NotFound.
Any ideas?
Based on everything I read, this is supposed to be pretty simple and just work - so I'm obviously making a very basic error.
I'm wondering if after I authenticate the user on my logon.aspx web page, I need to somehow pass an authenticated WebContext instance over from the logon page to my silverlight application instead of creating a new instance in the silverlight app startup code - but have no idea how to do that.
Appreciate any or all suggestions.
I suspect the Response.Redirect("...", true);
According to this article you should pass false to keep the session.

System.IO Exception: Logon failure: unknown user name or bad password

System.IO Exception: Logon failure: unknown user name or bad password.
1 minute ago | LINK
Hi All I am trying to resolve this issue with all possible solutions but could not succeed.
Requirement - I should be able to access XML file located in network share share folder for validation of users and other purposes.
Problem: I am able to access the XML file located in Network Share folder when debugging using VS 2010 but not when i published to IIS 7.
Methods Approached: I created a user account XXX and with password and made the user part of Administrators group. Set the website application pool identity to custome user account(XXX) created.
In the web.config I added a line:
<identity impersonate="true" userName="XXX" password="XXXXX"/>
Code where exception is caught-
string UserConfigXML ="\\\\servername\\Engineering\\Kiosk Back Up\\UserCFG.XML";
reader = new StreamReader(UserConfigXML);
string input = null;
string[] sArray;
while ((input = reader.ReadLine().Trim()) != "</USERS>")
{
if (input.Contains("<USER NAME="))
{
sArray = input.Split(new Char[] { '"' });
string sUserName = sArray[1].ToString().ToUpper();
string sDelivery = "";
while ((input = reader.ReadLine().Trim()) != ("</USER>"))
{
char[] array2 = new char[] { '<', '>' };
if (input.Contains("<DELIVERY_MECHANISM>"))
{
string[] mechanism = input.Split(array2);
sDelivery = mechanism[2].ToString().ToUpper();
if (sDelivery == "WEBMAIL")
{
UsersList.Add(sUserName);
}
}
}
}
}
return UsersList;
Any ideas how to resolve the issue?.
I propose 3 fixes for 2 different scenarios:
If you have both computers (server & computer holding the xml) hooked up using domain authentication: create a domain user and give it rights to access that file in the computer holding the xml.
Any other situation than the one mentioned above: create a user with the same name and password on both computers and set that as the one impersonated by the application pool.
(UNSECURE) Works in any scenario, without impersonation: put the XMLs in a network share that allows anonymous access.

System.Web.HttpException: Unable to validate data - after publishing site

I have written the following code for login:
Session["IsLogin"] = false;
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (txtPassword.Text.Trim() == string.Empty)
{
// Display Error
}
else
{
string Pwd = config.AppSettings.Settings["PWD"].Value.ToString();
FormsAuthenticationTicket formAuthTk = FormsAuthentication.Decrypt(Pwd);
string strDcryptedPwd = formAuthTk.Name.Trim().ToString();
if (txtPassword.Text.Trim() == strDcryptedPwd)
{
Session["IsLogin"] = true;
Response.Redirect("AnyPage.aspx");
}
else
{
// Error, Wrong password
}
}
Which is running fine while running through Visual studio. But when I published it it is showing the below error:
System.Web.HttpException: Unable to validate data
NOTE:
I publish the application on the
same server on which I am developing
the site.
I have tried EnableViewStateMAC =
false on page level. [Login Page]
What is the reson of this error? Why it is only appears when I have published the site?
I have changed the way to encrypt the string and the problem disapperars. I have no idea about the reason of the error, but I resolved it like this.
Hope it will help to others, who are facing the same issue.
you do not need to declare the config in the way you did, just use Configuration.AppSettings["PWD"].ToString()...
see here:
How to: Read Application Settings from the Web.config File

Resources