Authentication headers not sending in HttpWebRequest - httpwebrequest

I am connecting to a service using a HttpWebRequest. In the service logs, there are Authentication errors being logged, even though the information is correct. The vendor who set up the server with the service, has said that .NET does not send the authentication headers on the first try.
_Req.Credentials = new NetworkCredential(username, password);
When the request is sent, the server responds with needing the headers, which the request then sends. Is this correct, and is there a way to send it on the initial request?

See this question pointing to the answer in this article: add headers manually (even the first time).

HttpWebRequest request;
request.PreAuthenticate = true;

Related

How can we capture HTTPWebRequest in .net core using Fiddler

I am sending http request to sandbox api which sometimes returns positive response but sometimes it returns bad request with same request data and headers. So I want to debug this request using fiddler during I run the .net core code hitting that api.
But I am not able to find any way to that. Can any one please help me out for the same. I have tried following code to do this:
var requestMessage = GenerateRequestMessage(HttpMethod.Put, uri, query);
requestMessage.Content = new ObjectContent<T>(value, new JsonMediaTypeFormatter(), (MediaTypeHeaderValue)null);
IWebProxy proxy = new WebProxy("127.0.0.1", 8888);
HttpClient.DefaultProxy = proxy;
return _httpClient.SendAsync(requestMessage);
but fiddler is not capturing this api request.

Oauth request using RestSharp

I am trying to send oauth request to receive a token and no matter what I do I get an error that nonce was already used. So I decided to send that same request using Fiddler and everything worked flawlessly. The only issue I see is with the request body. I have to send grant_type=client_credentials in the body and it must be of application/x-www-form-urlencoded type. not Json nor XML. RestSharp describes adding JsonBody and XMLbody but both of those would set incorrect content type to the request. In my code I am trying to add the body the following way:
req.AddParameter("grant_type", "client_credentials", ParameterType.RequestBody)
Is that the correct way to add request body? I am also open to all suggestions to what else might be causing that error
Thank you
For OAuth, to generate a token the grant_type, code, client_secret etc. should be sent as an query parameters. In RestSharp it is done as
request.AddQueryParameter("grant_type", "client_credentials")
Everything in detail about OAuth is here

HTTP dataset credential error

In Azure Data Factory V2, I created a new http dataset an added a url and basic login details to connect to a https endpoint, when use the the Test Connection the response is "Connection successful"
When i try to "Preview data" it fails, the message from more is
The credential to read http file is invalid. Activity ID:89ae4de1-e6be-46fd-abb9-39360fe5323b.
How do i find out more about this error?
When I try the same url and basic login details in Postman I get back the expected results.
thanks
In Azure data factory, if basic auth type is specified, the http connector honor basic auth protocol, that means:
* It would send out a request without any credential first
* when the http server return 401 response with correct WWW-Authenticate header, it will continue enclose credential into next http request
So if your http server can't handle the request, you will get unauthorize error.
Postman can do it because postman ignored the first http request and send out the second one directly.
you can manually add header to your request:
Authorization: Basic ......
If you don't know how to generate it, you can copy it from postman, after passing credentials.
Best,
Pawel

HttpWebRequest to Okta result in Forbidden 403

I'm currently stumble on frustrating Forbidden 403 error when doing simple GET WebRequest to Okta. I've added my application url into Okta Admin > Security > API as CORS. Below is my code
string requestURL = "https://myokta.oktapreview.com/api/v1/users/me";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestURL);
request.Method = "GET";
request.Timeout = 120000;
request.ContentType = "application/json";
WebResponse response = request.GetResponse(); // exception Forbidden 403
I could copy paste the requestURL in internet browser and get the json response without any problem. And if I don't have session, it also return error code E0000005 - Invalid session.
If I cannot do it through WebRequest, any suggestion on which client to use in okta.core.dll ?
Please help me and any help would be very much appreciated. Thank you ...
Thanks for the info. There isn't any out-of-the-box solution for your use case, but I would strongly suggest that you switch to OpenID Connect. I have a .NET sample with a Single Page Application and a web API that demonstrates how you can deserialize the JWT token in the Web API to retrieve the user's identity. You can find at https://github.com/rlondner/okta-aspnet-spa_webapi-oidc/
When enabling CORS, please make sure that you type out the correct url.
For instance if you are running https locally, 'http://localhost:8080/' would be the correct url to enable. You also have to enable 'https://developer.okta.com' in Okta's developer console.

IIS 7 Serves GET request correctly to browser but throws timeout exception for API request

I am running a very simple Web application (Asp.Net MVC3) on Win 7 IIS.
I have a very simple HTTP GET API which returns hello world.
Calling:
http://localhost/helloworld
Returns:
Hello World!
This works perfectly over a browser.
But when I write an app which tries to pull this URL using a webclient, I get the following error:
{"Unable to read data from the transport connection: The connection was closed."}
My Code is as follows
WebClient web = new WebClient();
var response = web.DownloadString("http://localhost/helloworld");
My IIS Settings are as follows
What should I be looking at? I have been at this for hours and I have run out of options to try! Any help will be really appreciated!
Thanks.
I suspect it's because WebClient does not send some of the HTTP headers:
A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing. http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx
Try using HttpWebRequest instead. http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
I finally figured out what the issue was and instead of it being an IIS specific issue - which I was leaning towards, it turned out to be an issue with the code that I wrote.
Adding details here incase someone else runs into a similar problem.
I had the following method in my code which I was using to send the response of the request as a JSON object.
private void sendJsonResult(string result) {
Response.StatusCode = 200;
Response.Headers.Add("Content-Type", "application/json; charset=utf-8");
Response.Flush();
Response.Write(result);
Response.End();
Response.Close(); // <-- This is the problem statement
}
On digging around a bit, I found out that we should not be doing a Response.Close().
A better explanation of this is here.
Once I removed that line, it started working perfectly - both in my consuming app as well as the web browser, etc.
If you will read the link above, you will clearly understand why we should not be using a Response.Close() - so I will not go into that description. Learnt a new thing today.