Getting 400 Bad Request erro calling java web service - asp.net

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.

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;

CRMService.asmx - 401 Unauthorized error

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?

Do I need to investigate HTTP 401 cached by Fiddler during the HttpWebRequest post to ASP.NET WebApi server

I am totally new to WebApi and WebRequests and other things.
After hours of googling, finally, I managed to do POST using C# and HttpWebRequest.
When I do HttpWebRequest in debug mode using Visual Studio I do not get any exceptions.
My app work as I accept , I get data to webApi server and also get back data.
To be sure how my app communicate with WebApi server I start Fiddler Web Debugger.
During the POST to WebApi, Fiddler chace 401 errors
{"Message":"Authorization has been denied for this request."}
Steping step by step in debuger I fund that following lines of code doing 401 error
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Credentials = new NetworkCredential(username, password);
wr.Method = "POST";
wr.ContentType = "application/json";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(body);
wr.ContentLength = byteArray.Length;
using (System.IO.Stream dataStream = wr.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length); //After this line of code Fidler Chace HTTP 401
}
Later in code when I do wr.GetResponse() I do get status 200OK.
My questions are :
Do I need to redesign my code to avoid this error in Fiddler ?
Is there other methods to fill HttpWebRequest whit jsonSting beside using GetRequestStream() ?
If your service is enabled with Windows Authentcation, then in Fiddler, you can select the option to automatically authenticate using your logged on credentials by going here:
Composer tab -> Options tab -> Automatically Authenticate
Also, why not use HttpClient from System.Net.Http?...It has a much better and easy programming model...example:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9095/");
HttpResponseMessage response = client.PostAsJsonAsync<Customer>("api/values", cust).Result;

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);
}

Return large data from WCF Service to ASP.NET Web Service

So we have console-hosted WCF Service and ASP.NET WEB Service (on IIS).
After some tough operation WCF Service must return some (large) data to ASP.NET Web Service for next processing. I tested on small results and everything is ok.
But after testing on real data that is a serialized result object that is near 4.5 MB, an error occurs on ASP.NET Web Service, which is the client in wcf-client-server communication.
This is the error I got:
The socket connection was aborted. This could be caused by an error
processing your message or a receive timeout being exceeded by the
remote host, or an underlying network resource issue. Local socket
timeout was '04:00:00'. Inner Exception: SocketException:"An existing
connection was forcibly closed by the remote host" ErrorCode = 10054
Messages size are configured by next binding (on server and client):
NetTcpBinding netTcpBinding = new NetTcpBinding();
netTcpBinding.TransactionFlow = true;
netTcpBinding.SendTimeout = new TimeSpan(0, 4,0, 0);
netTcpBinding.Security.Mode = SecurityMode.None;
netTcpBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
netTcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
netTcpBinding.Security.Transport.ProtectionLevel = ProtectionLevel.None;
netTcpBinding.MaxReceivedMessageSize = 2147483647;
netTcpBinding.MaxBufferSize = 2147483647;
netTcpBinding.MaxBufferPoolSize = 0;
netTcpBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
netTcpBinding.ReaderQuotas.MaxArrayLength = int.MaxValue;
netTcpBinding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
netTcpBinding.ReaderQuotas.MaxDepth = 32;
netTcpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;
MaxObjectsInGraph property is configured in a config file.
What can you advise me? And also I need example how programmatically set MaxObjectsInGraph property on client and server.
Thanks for answers.
Problem is fixed by setting programmatically MaxObjectsInGraph(for serializer) as a service attribute.

Resources