CRMService.asmx - 401 Unauthorized error - asp.net

CRM Portal is setup on "crmstaging" machine, on port 5555.
Following is the path of CRM Service:
http://crmstaging:5555/MSCrmServices/2007/CrmService.asmx
I am creating an ASP.NET Website on my dev machine "crmdev", and have added reference of the above service.
Now, I am trying to use various methods of this service to perform operations on my CRM entities, for that, I have written following code in button click of the page:
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "MyCompany";
CrmService service = new CrmService();
service.CrmAuthenticationTokenValue = token;
service.Credentials = new System.Net.NetworkCredential("username","password","domainname");
//service.Credentials = System.Net.CredentialCache.DefaultCredentials;
string fetch1 = #"<fetch mapping=""logical"">
<entity name=""account"">
<all-attributes/>
</entity>
</fetch>";
String result1 = service.Fetch(fetch1);
txtBox1.Text = result1;
In above code, I have passed credentials of the user having access on CRM Staging machine.
While trying to execute this code, I get an error saying "401 Unauthorized".
How to resolve this issue?

Related

SQL Server Report Server (SSRS) via WCF: HTTP request is unauthorized with client authentication scheme 'Ntlm'

I have a .Net Core 3.1 application which is trying to connect to a SQL Server Report Server via WCF, in order to programmatically generate reports on demand.
But the program is not able to authenticate against the Report Server.
Here is the relevant program code:
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxReceivedMessageSize = 10485760; //10MB limit
// Create the execution service SOAP Client
var rsExec = new ReportExecutionServiceSoapClient(
binding,
new EndpointAddress("http://my-ssrs/ReportServer")
);
// Setup access credentials.
var clientCredentials = new NetworkCredential(
"MyReportServerUserName",
"MyReportServerPassword",
"."
);
if (rsExec.ClientCredentials != null)
{
rsExec.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Impersonation;
rsExec.ClientCredentials.Windows.ClientCredential = clientCredentials;
}
// ************************************************
// Get following Exception when next line executes.
// ************************************************
await rsExec.LoadReportAsync(null, "/path-to/my-report", null);
When the last line ("rsExec.LoadReportAsync") is executed, I get the following exception:
The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'NTLM'.
The Report Server is on the same Windows Domain.
After some research, I've tried changing the ClientCredentialType = HttpClientCredentialType.Windows but this generated a different exception, as follows:
The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'.
Does anyone have any suggestions about what I might try?
Had the same problem. Solved it by additionally setting the proxy credential type:
binding.Security.Transport.ProxyCredentialType = System.ServiceModel.HttpProxyCredentialType.Ntlm;

google analytics apis not working in production

I am trying to use the google analytics apis v3 to embed the analytics graph to my website using Certificate file. I got it to work on the local machine but when I deploy the code to my web server it produces this error:
The remote server returned an error: (400) Bad Request.
Does anyone know what is causing this error message and why I can't get the google graph on my production website?
Here is the code that is working on my local machine:
string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
x509Certificate2File = HttpContext.Current.Server.MapPath("~/App_Data/privatekey.p12"),
x509Certificate2FilePassword = "notasecret",
serviceAccountId = "xxxxxxx#developer.gserviceaccount.com",
profileId = "ga:xxxxxxxx",
startDate = "2013-10-06",
endDate = "2013-11-07";
AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
X509Certificate2 key = new X509Certificate2(x509Certificate2File, x509Certificate2FilePassword, X509KeyStorageFlags.Exportable);
AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = serviceAccountId, Scope = scope };
OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = auth });
DataResource.GaResource.GetRequest request = gas.Data.Ga.Get(profileId, startDate, endDate, "ga:visits");
request.Dimensions = "ga:day";
request.MaxResults = 10;
/* error 400 occur here on the production */
Google.Apis.Analytics.v3.Data.GaData data = request.Execute();
Thanks
There is only one possibility and without looking at the code you're going to have to chase it down; one of the paths are wrong and needs to be changed. This could be in the form of an IP address as well when I say "path" as you are calling something that is not there. It worked fine on your local machine (correct path) and it gave a 400 on the remote one (bad request) as in calling the wrong place.

Dot Net Client and IIS hosted SignalR with Win auth

Is there a way to configure the .NET client so that it will work with a IIS hosted SingalR that uses Windows authentication?
If I disable windows authentication it works, but this is not an option
setting connection.Credentials = CredentialCache.DefaultCredentials does not help.
The code
public EventProxy(IEventAggregator eventAggregator, string hubUrl)
{
typeFinder = new TypeFinder<TProxyEvent>();
subscriptionQueue = new List<EventSubscriptionQueueItem>();
this.eventAggregator = eventAggregator;
var connection = new HubConnection(hubUrl);
connection.Credentials = CredentialCache.DefaultCredentials;
proxy = connection.CreateHubProxy("EventAggregatorProxyHub");
connection.Start().ContinueWith(o =>
{
SendQueuedSubscriptions();
proxy.On<object>("onEvent", OnEvent);
});
}
ContinueWith triggerst directly after Start and when the first subscription comes in I get a
The Start method must be called before data can be sent.
If I put a watch on the DefaultCredentials I can see that Username, Domain and Password are all String.Empty. Its a standard Console program, Enviroment.Username returns my username
Sure, set connection.Credentials = CredentialCache.DefaultCredentials. More details about credentials here http://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultcredentials.aspx.

Publishing with Core Service and Impersonation

I have a Tridion Core Service Web Application to publish pages. When logged into the server and running it from there via a browser client calling a web service with ajax it works fine. However, when I run the application from my desktop it does nothing, and also throws no error messages.
*Edit:
The Web App hosting the web service is running as an 'Application' under the Tridion 2011 CMS website. This is done to avoid cross-domain ajax issues/
Update: The code below is working fine - both with the impersonate and also with Nick's solution. My issue was actually in how I was calling the web service from jQuery and using the appropriate URL. I am leaving the code and question so maybe it will help others.
My code is:
string binding = "wsHttp_2011";
using (var client = new SessionAwareCoreServiceClient(binding))
{
client.Impersonate("company\\cms_svc");
// ** Get Items to Publish
List<string> itemsToPublish = GetItemsToPublish(publishItem.TcmUri, client);
PublishInstructionData instruction = new PublishInstructionData
{
ResolveInstruction = new ResolveInstructionData() { IncludeChildPublications = false },
RenderInstruction = new RenderInstructionData()
};
PublicationTargetData pubtarget = (PublicationTargetData)client.Read(publishItem.PubTargetUri, readoptions);
List<string> target = new List<string>();
target.Add(pubtarget.Id);
client.Publish(itemsToPublish.ToArray(), instruction, target.ToArray(), GetPublishPriority(publishItem.Priority), readoptions);
}
Have at look at this page on SDL Live Content, which explains various types of scenarios for connecting as different users:
http://sdllivecontent.sdl.com/LiveContent/content/en-US/SDL_Tridion_2011_SPONE/task_87284697A4BB423AAD5387BBD6884735
As per the docs, instead of impersonation you may want to establish your Core Service connection as follows using NetworkCredential:
using (ChannelFactory<ISessionAwareCoreService> factory =
new ChannelFactory<ISessionAwareCoreService>("netTcp_2011"))
{
NetworkCredential networkCredential =
new NetworkCredential("username", "password", "domain");
factory.Credentials.Windows.ClientCredential = networkCredential;
ISessionAwareCoreService client = factory.CreateChannel();
Console.WriteLine(client.GetCurrentUser().Title);
}

Getting 400 Bad Request erro calling java web service

I am connecting to a java web service from my asp.net app ,but I am getting a 400 Bad request exception.
I have added a web reference in my project and using that to connect in the code as follows :
client is the web service reference object.
NetworkCredential credentials = new NetworkCredential("", "");
client.Credentials = credentials;
client.PreAuthenticate = true;
client.RequestEncoding = Encoding.UTF8;
object response = client.getmethod(req);
I also tried putting in
client.UnsafeAuthenticatedConnectionSharing = true;
client.AllowAutoRedirect = true;
but it still does not work and gives me the same error. The request is working if i try from Soap-UI from my machine.
To Add, I am getting a ClientProtocol error in SoapUI also if i don't select authentication type as "PreEmptive". Is there a way to set this in asp.net.
Any thoughts would be appreciated.

Resources