CRM 2011 Online via an ASP.net application does not work, same code via Console Application Works -> "Authentication Failure"-error - asp.net

I'm trying to connect to a CRM 2011 Online environment. I'm able to connect via a "Console Application", but when I'm trying to connect via an "ASP.net"-application with the same code, it doesn't work, it gives me the "Authentication Failure"-error ({"An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail."}).
Is there something special we need to do to make it work on an "ASP.net" environment. I tested out several solutions I found on the internet, but all gives me the same error.
A "code"-snippet of my simplified code:
private static ClientCredentials GetDeviceCredentials()
{
return Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
}
protected void Button1_Click(object sender, EventArgs e)
{
//Authenticate using credentials of the logged in user;
string UserName = "*****"; //your Windows Live ID
string Password = "*****"; // your password
ClientCredentials Credentials = new ClientCredentials();
Credentials.UserName.UserName = UserName;
Credentials.UserName.Password = Password;
Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
//This URL needs to be updated to match the servername and Organization for the environment.
Uri OrganizationUri = new Uri("https://*****.crm4.dynamics.com/XRMServices/2011/Organization.svc"); //this URL could copy from Setting --> Developer Source
Uri HomeRealmUri = null;
//OrganizationServiceProxy serviceProxy;
using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, GetDeviceCredentials()))
{
IOrganizationService service = (IOrganizationService)serviceProxy;
OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
var theAccounts = orgContext.CreateQuery<Account>().Take(1).ToList();
Response.Write(theAccounts.First().Name);
}
}
I tried several things, like deleting the content of "LiveDeviceID"-folder an re-running the device registration tool. but is weird that it works in the "console application" but not on my "asp.net"-solution...
PS : I am able to generate the "context"-file via crmsvcutil.exe /url:https://org.crm4.dynamics.com/XRMServices/2011/Organization.svc /o:crm.cs /u:username /p:password /di:deviceUserName /dp:devicPWD

Is there any particular reason you have
Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
You shouldn't need that line for windows live authentication.
Even with that the code seems valid so it is something to do with the Device Registration. I suggest rather than just call it directly like you have
using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, GetDeviceCredentials()))
{
You try something like the following because you only need to register once:
ClientCredentials deviceCredentials;
if ((CRMSettings.Default.DeviceID == String.Empty) || (CRMSettings.Default.DevicePassword == String.Empty))
{
deviceCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.RegisterDevice();
}
else
{
deviceCredentials = new ClientCredentials();
deviceCredentials.UserName.UserName = CRMSettings.Default.DeviceID;
deviceCredentials.UserName.Password = CRMSettings.Default.DevicePassword;
}
using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, deviceCredentials))
{
I have had issues in the past where I get an "already registered" response from the RegisterDevice call.
I would also dump out the Device ID and Password so you can see if they are being set.

Related

HttpClient and WebClient requests / responses don't work for intranet with DefaultCredentials

Problem: I am unable to get content from an company internal webpage through using HttpClient or WebClient. I am able to get the content by accessing the URL directly, however.
Details: .NET Core 3.1 Razor Pages, IIS 10, Windows Authentication.
I have a website http://myintranet/Editor/Bib/4343 where a user can press a button to generate a static page. Behind the scenes, it attempts to read a stream from http://myintranet/Editor/NewBib/4343/true and create a static HTML page from it.
When clicking the button, the response is always IIS 10.0 Detailed Error - 401.1 - Unauthorized etc.
However when I access the webpage directly in the browser, it opens up just fine (note that if it is the first time accessing the website, I am prompted by the browser to enter my username and password. After that, the browser remembers these credentials).
Also note that when running it from localhost through Visual Studio, all works fine, the static page downloads properly too.
Here is my code:
Version 1:
public IActionResult OnPostGenerateStaticPage()
{
try
{
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true, PreAuthenticate = true });
HttpResponseMessage response = client.GetAsync(Url.PageLink().Replace("Bib", "NewBib") + "/true").Result;
var indexPageContents = response.Content.ReadAsStreamAsync().Result;
var cd = new System.Net.Mime.ContentDisposition
{
FileName = BibNumber + ".htm",
Inline = false,
};
Response.Headers.Add("Content-Disposition", cd.ToString());
return File(indexPageContents, "text/html");
}
catch (IOException)
{
return RedirectToPage("./Bib");
}
}
Version 2:
public IActionResult OnPostGenerateStaticPage()
{
try
{
WebClient client = new WebClient { UseDefaultCredentials = true };
string desiredUrl = Url.PageLink().Replace("Bib", "NewBib") + "/true";
var indexPageContents = client.OpenRead("desiredUrl");
var cd = new System.Net.Mime.ContentDisposition
{
FileName = BibNumber + ".htm",
Inline = false,
};
Response.Headers.Add("Content-Disposition", cd.ToString());
return File(indexPageContents, "text/html");
}
catch (IOException)
{
return RedirectToPage("./Bib");
}
}
Another thing, I have asked the web server admin to check that NTLM is above Negotiate for the authentication providers for this website and it is. Also, Anonymous and Basic Authentication are disabled and Windows Authentication is enabled.
Not sure where to go from here...

Accessing client certificates smartcard with web application

I need to fetch the certificate, and would like to fetch the client, and there is no server, I could do this form:
public static X509Certificate2 EscolherCertificado(string serial)
{
var store = new X509Store("MY", StoreLocation.CurrentUser);
var Key = new RSACryptoServiceProvider();
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = store.Certificates;
X509Certificate2Collection fcollection = collection.Find(X509FindType.FindBySerialNumber, serial, false);
if (fcollection.Count == 1)
{
return fcollection[0];
}
else { cod = "00000"; msgm = "not found"; return null; }
}
But when I publish on the server it does not work. Is there any way I can do this?
I can not get the client certificate, it returns error, because on the server there are no registered certificates.
EDIT
I have already been told that it is possible, I just do not know how to do it, the ways I tried does not work.
EDIT
Following this link, I did comply, but it does not work, it does not always find. What can I do to correct this problem?
public static X509Certificate2 EscolherCertificado(string serial)
{
X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
userCaStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySerialNumber, serial, true);
X509Certificate2 clientCertificate = null;
if (findResult.Count == 1)
{
clientCertificate = findResult[0];
}
else
{
throw new Exception("Unable to locate the correct client certificate.");
}
cod = "0000"; msgm = clientCertificate.ToString(); return clientCertificate;
}
catch
{
throw;
}
finally
{
userCaStore.Close();
}
As far as I know, you cannot reach the client Certificates Store.
To do that you have to code a propietary plugin for each browser platform and give the right access permissions to the client.
That's a very painful task.
I wish you good luck with it.
In my case we ended up developing an EXE which has full access to the client hardware and features of the platform.
Here's the code:
private void ElegirCert()
{
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store("MY", System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
System.Security.Cryptography.X509Certificates.X509Certificate2Collection collection = (System.Security.Cryptography.X509Certificates.X509Certificate2Collection)store.Certificates;
System.Security.Cryptography.X509Certificates.X509Certificate2Collection fcollection = (System.Security.Cryptography.X509Certificates.X509Certificate2Collection)collection;//.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByTimeValid, DateTime.Now, false);
try
{
Cert = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(fcollection, "Elegir", "Seleccione el certificado que desea utilizar", System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection)[0];
}
catch (Exception e)
{
}
store.Close();
}
I still think that it is not possible to get the list of client certificates using the sole browser capabilities.
There is a way and it involves creating an extension which communicates with an Executable Native file that does the "hard work". That means, getting the full list of certificates and exposing it to the user.
I think that after that, the user chooses one, then the EXE asks for the cert store password (if it has one), then the exe digitally signs the hash and whatever...

Unknown username or bad password, LDAP Active Directory

I'm trying to authenticate against AD using application mode (ADAM), but keep getting unknown username or bad password. If I test the login in LDP.exe it logs in no problem, on simple bind. I've trawled through all similar posts with the same issue, but have not resolved it, any suggestions what I should be checking for?
private bool ValidateActiveDirectoryLogin(string Username, string Password)
{
bool Success = false;
System.DirectoryServices.DirectoryEntry Entry = new System.DirectoryServices.DirectoryEntry("LDAP://localhost:389/OU=Users,O=TestDirectory", Username, Password);
System.DirectoryServices.DirectorySearcher Searcher = new System.DirectoryServices.DirectorySearcher(Entry);
Searcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
try
{
System.DirectoryServices.SearchResult Results = Searcher.FindOne();
Success = (Results != null);
}
catch (Exception ex)
{
Success = false;
throw;
}
return Success;
}
Determine what context your application is hitting AD with. If your ASP.NET application pool identity is one that is low privileged, it won't have enough permissions to query active directory. If you don't want to create a custom user to run the app pool as with appropriate permissions - you could use the LogonUser API to make your ValidateActiveDirectoryLogin call under the security context of that account.
Finally, you should consider using System.DirectoryServices.AccountManagement if you are using .NET 3.5 or above.
You can use code like
bool validCreds = false;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
validCreds = context.ValidateCredentials( username, password );
}

System.DirectoryServices - The server is not operational

I get an error by a website, on which I use Windows Authentication.
Strange things:
Only occurs if user is not yet saved into database (new unknown user)
Appears only on live system, everything fine on local development environment
This is what I get in a logging mail:
Source : System.DirectoryServices
Message: The server is not operational.
Trace:
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
at Smarthouse.Labs.DataAccess.UserListManager.SaveUser(String windowsUserName)
This is how I implement DirectorySearch:
private void SaveUser(string windowsUserName)
{
string[] domainAndUser = windowsUserName.Split('\\');
string domain = domainAndUser[0];
string username = domainAndUser[1];
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher search = new DirectorySearcher(entry);
try
{
// Bind to the native AdsObject to force authentication.
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("sn");
search.PropertiesToLoad.Add("givenName");
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne();
if (result == null)
{
throw new Exception("No results found in Windows authentication.");
}
User userToSave = new User();
userToSave.FirstName = (String) result.Properties["givenName"][0];
userToSave.LastName = (String) result.Properties["sn"][0];
userToSave.Email = (String) result.Properties["mail"][0];
userToSave.Username = windowsUserName;
userToSave.Guid = Guid.NewGuid();
SaveUser(userToSave);
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message, ex);
}
finally
{
//Dispose service and search to prevent leek in memory
entry.Dispose();
search.Dispose();
}
}
If more code examples are needed just tell me.
Your problem is that you're using a "plain" domain name to bind - this won't work in LDAP. Actually, if you try to bind to LDAP://MyDomain, what you're really doing is trying to bind to the server called MyDomain.
You need a valid LDAP bind string - something like LDAP://dc=yourdomain,dc=local or something.
To find out what your default LDAP binding context is, use this code snippet:
DirectoryEntry deRoot = new DirectoryEntry("LDAP://RootDSE");
if (deRoot != null)
{
string defaultNamingContext = deRoot.Properties["defaultNamingContext"].Value.ToString();
}
Once you have that string - use that as your bind string to your LDAP server.
And if you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context -- no domain name needed, uses default domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
if(user != null)
{
// do something here....
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
You can use bind strings in the format LDAP://mydomain.com:389. I kept getting "Access is Denied" when trying to use the format LDAP://DC=mydomain,DC=com. Once I switched to the LDAP://mydomain.com:389 format, and bound using the AuthenticationTypes.ServerBind flag when constructing my DirectoryEntry, it worked great. This was in Azure App Service.
To add to marc_s's answer above, I needed to search multiple domains.
So for each Domain I did the following:
DirectoryEntry deRoot = new DirectoryEntry("LDAP://" +"DomainName"+ "/RootDSE");
string defaultNamingContext = "LDAP://" + deRoot.Properties["defaultNamingContext"].Value.ToString();
DirectoryEntry mySearchRoot = new DirectoryEntry(defaultNamingContext);
DirectorySearcher myDirectorySearcher = new DirectorySearcher(mySearchRoot);
Similar Error Happened to me (though it happened all the time and not in specific cases like pointed out here) because of a wrong Active Directory connection string. i used the corp instead the prod one .
Use something that works for another app in your organization if exists.

Report Server Credentials and Missing End Point Exception

Actually what I needed was a step by step guide but anyway..
I have to show some rdl reports in a web-site using the ASP.NET report vievew and do all the necessary configurations for the Reporting Services. The users of the page should not deal with ANY authorization.
Here is my code for the report viewer:
rprtView.ServerReport.ReportServerCredentials = new ReportServerCredentials();
rprtView.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
rprtView.ServerReport.ReportServerUrl = new Uri(#"http://mydomain/reports");
rprtView.ServerReport.ReportPath = #"/MyReports/PurchaseOrder";
rprtView.ShowParameterPrompts = false;
ReportParameter[] parameters = new ReportParameter[1];
parameters[0] = new ReportParameter();
parameters[0].Name = "OrderNumber";
parameters[0].Values.Add(orderNumber);
rprtView.ServerReport.SetParameters(parameters);
rprtView.ServerReport.Refresh();
Here is my overload for IReportServerCredentials
public class ReportServerCredentials : IReportServerCredentials
{
public bool GetFormsCredentials(out Cookie authCookie, out string userName, out string password, out string authority)
{
authCookie = null;
userName = password = authority = null;
return false;
}
public WindowsIdentity ImpersonationUser
{
get { return null; }
}
public ICredentials NetworkCredentials
{
get { return new NetworkCredential("myUserName", "myPassword"); }
}
}
I am able to login to "http://mydomain/reports", the default web site of the SSRS, using "myUserName" and "myPassword" (I am not sure if this is related). Still I am getting MissingEndPoint exception at SetParameters() method above. It says:
"The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version."
I am also responsible for configuring the Reporting Services for the necessary configuration for this scenario and I have heard that this issue is related to the config files in SSRS but I have no idea what to write in them. Any help is much appreciated!
The string provided for rprtView.ServerReport.ReportServerUrl should be for the Report Server service, not the Report Manager application.
Change this:
rprtView.ServerReport.ReportServerUrl = new Uri(#"http://mydomain/reports");
to this:
rprtView.ServerReport.ReportServerUrl = new Uri(#"http://mydomain/reportserver");
This page has some high-level info on the Report Manager interface, Report Server web service, and how they relate.

Resources