HttpWebRequest doesn't seem to "get" my proxy credentials - c#

I have a REST-based web service I'm trying to connect to, and while it works just fine from my local dev machine, I am trouble getting it to work on my client's test system which is behind a web proxy.
I have this code snippet here:
HttpWebRequest request = WebRequest.Create(targetUrl) as HttpWebRequest;
if (request == null)
return;
request.Method = "GET";
request.Accept = "application/json";
request.Credentials = new NetworkCredential("myusername", "mytopsecretpassword");
WebProxy webProxy = new WebProxy("myproxy.net", 8080)
{
Credentials = new NetworkCredential("myusername", "mytopsecretpassword"),
UseDefaultCredentials = false
};
request.Proxy = webProxy;
But when I try to execute this call and get back the response like this:
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
I keep getting an error:
System.Net.WebException
The remote server returned an error: (407) Proxy Authentication Required.
WTF ?!?! I'm setting up my proxy and I'm providing the proxy credentials.... what more can I do?

Try adding the domain to the proxy credentials.
I'd also try setting UseDefaultCredentials = false before you set the new credentials.

Related

Send HTTP request with "Negotiate Authorization"

How can I send an HTTP request with Negotiate Authorization header attribute from a .NET (C#) application?
I tried the following, but Authorization attribute was not added to the request...
...
string url = ...;
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
...
private CredentialCache GetCredential()
{
string url = ...;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new System.Uri(url), "Ntlm", new NetworkCredential(username, pwd, domain));
return credentialCache;
}
My experience with using a network credential in a WebRequest is that the request.GetResponse() does NOT pass the credential unless it receives an Unauthorized (challenge) response from the server. If it does receive a 403, it will automatically fire a second request which includes the credential. Make sure the end point you are hitting returns a 401 if the Auth header is missing.

The remote server returned an error: (401) Unauthorized at System.Net.HttpWebRequest.GetResponse()

I am trying to run following code it works fine when runs on localhost IIS but returns error when hosted on my web server IIS
Error : -- The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse() at _Default.btnsubmit_Click(Object sender, EventArgs e) in e:\WebSite1\Default.aspx.cs:
try
{
var webAddr = "http://serviceserver/someService";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "text/xml";
httpWebRequest.ContentLength = 0;
httpWebRequest.Method = "GET";
httpWebRequest.Credentials = new NetworkCredential("user", "password");
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new treamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Label1.Text = result;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.StackTrace);
Response.Write(ex.InnerException);
}
Update
The above service URL is WCF service and it is secured via transport credentials in windows
I am trying to hit this URL via my web application and passing my credentials as Network Credentials.
When I run this web application on my local machine it runs fine and returns the required data.
But when I host this application I got above stated error. Am I doing something wrong.
You need to look on your server for a username, pass, and if it is basic or digest. I set my command up like this:
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
var cache = new CredentialCache();
cache.Add(new Uri(uri), "Digest", new NetworkCredential("administrator", "admin"));
httpRequest.Credentials = cache;
httpRequest.PreAuthenticate = true;
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
//DO CODE
}
Before implementing an httpRequest in code, you should check it in a browser first. Enter your link in a browser and see if it brings up what you want.

WebRequest with proxy throwing HTTP 405 method not allowed error

I'm making simple HTTP GET request to website using WebRequest. When I add proxy details,getting HTTP 405 method not allowed error.
Below is my code:
WebRequest req = HttpWebRequest.Create(uri);
//WebProxy prr = new WebProxy();
WebProxy proxy = new WebProxy("xxxxx");
req.Credentials = CredentialCache.DefaultCredentials;
req.Method = "GET";
req.Proxy = proxy;
HttpWebResponse resp=req.GetResponse();
"xxxx" is our org proxy URL.
It's working fine WITHOUT proxy, but I need to make it to work with proxy details.
Am I missing anything?.
Along with the proxy you may need to mention the port also. See the code below
string ipAddrs= "proxy ip ";
WebProxy proxy = new WebProxy(ipAddrs,3128);
default proxy port number is 3128

Proxy Basic Authentication in C#: HTTP 407 error

I am working with a proxy that requires authentication, i.e., in a browser if I try to open a page it will immediately ask for credentials. I supplied same credentials in my program but it fails with HTTP 407 error.
Here is my code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
IWebProxy proxy = WebRequest.GetSystemWebProxy();
CredentialCache cc = new CredentialCache();
NetworkCredential nc = new NetworkCredential();
nc.UserName = "userName";
nc.Password = "password";
nc.Domain = "mydomain";
cc.Add("http://20.154.23.100", 8888, "Basic", nc);
proxy.Credentials = cc;
//proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Proxy = proxy;
request.Proxy.Credentials = cc;
request.Credentials = cc;
request.PreAuthenticate = true;
I have tried every possible thing but seem like I am missing something.
Is it something like, I have to make two requests? First with out credentials and once I hear back from server about need for credentials, make same request with credentials?
This method may avoid the need to hard code or configure proxy credentials, which may be desirable.
Put this in your application configuration file - probably app.config. Visual Studio will rename it to yourappname.exe.config on build, and it will end up next to your executable. If you don't have an application configuration file, just add one using Add New Item in Visual Studio.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
</configuration>
I was getting a very similar situation where the HttpWebRequest wasn't picking up the correct proxy details by default and setting the UseDefaultCredentials didn't work either. Forcing the settings in code however worked a treat:
IWebProxy proxy = myWebRequest.Proxy;
if (proxy != null) {
string proxyuri = proxy.GetProxy(myWebRequest.RequestUri).ToString();
myWebRequest.UseDefaultCredentials = true;
myWebRequest.Proxy = new WebProxy(proxyuri, false);
myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
and because this uses the default credentials it should not ask the user for their details.
here is the correct way of using proxy along with creds..
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
IWebProxy proxy = request.Proxy;
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
Console.WriteLine("Proxy is null; no proxy will be used");
}
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://20.154.23.100:8888");
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
myProxy.Address = newUri;
// Create a NetworkCredential object and associate it with the
// Proxy property of request object.
myProxy.Credentials = new NetworkCredential("userName", "password");
request.Proxy = myProxy;
Thanks everyone for help... :)
This problem had been bugging me for years the only workaround for me was to ask our networks team to make exceptions on our firewall so that certain URL requests didn't need to be authenticated on the proxy which is not ideal.
Recently I upgraded the project to .NET 4 from 3.5 and the code just started working using the default credentials for the proxy, no hardcoding of credentials etc.
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
I had a similar problem due to a password protected proxy server and couldn't find much in the way of information out there - hopefully this helps someone. I wanted to pick up the credentials as used by the customer's browser. However, the CredentialCache.DefaultCredentials and DefaultNetworkCredentials aren't working when the proxy has it's own username and password even though I had entered these details to ensure thatInternet explorer and Edge had access.
The solution for me in the end was to use a nuget package called "CredentialManagement.Standard" and the below code:
using WebClient webClient = new WebClient();
var request = WebRequest.Create("http://google.co.uk");
var proxy = request.Proxy.GetProxy(new Uri("http://google.co.uk"));
var cmgr = new CredentialManagement.Credential() { Target = proxy.Host };
if (cmgr.Load())
{
var credentials = new NetworkCredential(cmgr.Username, cmgr.Password);
webClient.Proxy.Credentials = credentials;
webClient.Credentials = credentials;
}
This grabs credentials from 'Credentials Manager' - which can be found via Windows - click Start then search for 'Credentials Manager'. Credentials for the proxy that were manually entered when prompted by the browser will be in the Windows Credentials section.
You can use like this, it works!
WebProxy proxy = new WebProxy
{
Address = new Uri(""),
Credentials = new NetworkCredential("", "")
};
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
HttpClient client = new HttpClient(httpClientHandler);
HttpResponseMessage response = await client.PostAsync("...");
try this
var YourURL = "http://yourUrl/";
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = true,
};
Console.WriteLine(YourURL);
HttpClient client = new HttpClient(handler);

Capturing html code from a website - The remote server returned an error: (407) Proxy Authentication Required

I'd like to capture the HTML code off a page and place it into a text file. Unfortunatel I get an error of the following:
"The remote server returned an error: (407) Proxy Authentication Required."
Anyone know how to solve this?
string url = #"http://www.panalpina.com/www/global/en/tools_resources/unit_converter/currency_codes.html";
HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET";
// make request for web page
myWebRequest.ToString();
HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
string myPageSource = string.Empty;
myPageSource = myWebSource.ReadToEnd();
myWebResponse.Close();
`
It seems you are using proxy server to connect to internet.
If yes add next code before http request send:
myWebRequest.Proxy = new WebProxy("you_proxy_machine", 8080 /*port*/);
myWebRequest.Proxy.Credentials = new NetworkCredential("proxy_username", proxy_password");

Categories