System.Net.WebClient fails weirdly - c#

I am trying to download some data from the reporting services instance on our TFS server.
Given that the code should run on a computer that is not domain-joined, I figured that I would set the credentials myself. No luck, got a HTTP 401 Unauthorized back. Ok, so I hooked up Fiddler to see what was happening.
But that's when I got Heisenberged - the call now went through without a hitch. So the authentication goes through with Fiddler connected, but fails without it. Is the Webclient broken or am I missing something profound here?
private void ThisWorksWhenDomainJoined()
{
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultNetworkCredentials;
wc.DownloadString("http://teamfoundationserver/reports/........"); //Works
}
private void ThisDoesntWork()
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username", "password", "domain");
wc.DownloadString("http://teamfoundationserver/reports/........"); //blows up wih HTTP 401
}

Take a look at this link:
HTTP Authorization and .NET WebRequest, WebClient Classes
I had the same problem as you. I have only added one line and it started to work. Try this
private void ThisDoesntWork()
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username", "password", "domain");
//After adding the headers it started to work !
wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
wc.DownloadString("http://teamfoundationserver/reports/........"); //blows up wih HTTP 401
}

Try this ...
var credCache = new CredentialCache();
credCache.Add(new Uri("http://teamfoundationserver/reports/........""),
"Basic",
new NetworkCredential("username", "password", "DOMAIN"));
wc.Credentials = credCache;
If that does not work, try replacing "Basic" with "Negotiate".

What happens when you use this?
wc.Credentials = CredentialCache.DefaultCredentials;
Also, are you sure you have the correct username, password and domain?
Also: I wonder if Fiddler is changing around some unicode characters when .net breaks them or something like that. If your user/pass/domain has unicode, try escaping it out like "\u2638" instead of "☺".

I was able to get around this error by using a CredentialCache object, as follows:
WebClient wc = new WebClient();
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri("http://mydomain.com/"), "Basic",
new NetworkCredential("username", "password"));
wc.Credentials = credCache;
wc.DownloadString(queryString));

Related

HttpWebRequest error 401 on Pi3 with IoT Core c#

I've used the search funktion before but the Solutions won't help in my case (don't know why). I've written a Code to call a IIS Webservice. The Code will run on my Desktop without any issues. On my Pi3 i will get an
(One or more errors occurred. (The remote server returned an error: (401) Unauthorized.)
error. What I'm doing wrong?
Thx Forward for helping me.
Uri uri = new Uri(Url); //TempUrl is assigned a string beforehand
request = HttpWebRequest.Create(uri);
// Add authentication to request
NetworkCredential c = new NetworkCredential("USER", "PASSWORD","DOMAIN");
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(uri, "NTLM", c);
request.Credentials = c;
Task<WebResponse> x = request.GetResponseAsync();
x.Wait(20000);
response = x.Result;
// Get the response stream into a reader
reader = new StreamReader(response.GetResponseStream());
Got it. I've Change the NetworCredentials as follows:
NetworkCredential c = new NetworkCredential(#"<Domain>\<USER>", "<PASSWORD>");
I don't know why, but it works.

C# webrequest to curl

I need to make a GET request to following url
[ ~ ] $ curl -u duff:X https://subs.pinpayments.com/api/v4/sitename/subscribers/7388.xml
where -u is username and then X is password.
How to use WebRequest?
Please suggest
The WebRequest class has a Credentials property, which you can set:
WebRequest request = WebRequest.Create(uri);
request.Credentials = new NetworkCredential("username", "password");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Another possibility would be to use the WebClient class, that supports custom credentials too:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
//Byte[] pageData = client.DownloadData(url);
//string pageHtml = Encoding.ASCII.GetString(pageHtml);
// or DownloadString: http://msdn.microsoft.com/en-us/library/fhd1f0sw%28v=vs.110%29.aspx
var pageHtml = client.DownloadString(uri);
Console.WriteLine(pageHtml);
If you need for a reason to set custom header information for the request, then the WebClient class could be more suitable.

Webrequest doesn't include authentication header

I am running the following in c# to send a login request to an API. However, according to Fiddler, it is not sending an Authentication Header. I am a rookie, so it is likely something simple.
NetworkCredential netcreds=new NetworkCredential(username,password);
CredentialCache credentials = new CredentialCache();
credentials.Add(new Uri(LoginUrl.ToString()),"Basic",netcreds);
Uri LoginUri = new Uri(LoginUrl);
WebRequest AuthRequest = WebRequest.Create(LoginUri);
AuthRequest.Credentials = credentials; `
AuthRequest.Headers.Add(HttpRequestHeader.AcceptEncoding,#"application/*+xml;version=1.5");`

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

webclient 401 into c#

I'm have some problems to use webclient.
When I try it:
var client = new WebClient();
client.Credentials = new NetworkCredential("intranet.homolog", "S3br#32011", "na-sebrae");
var html = client.DownloadData("http://www.intranet.sebrae.com.br/noticias/todas-as-notícias/rss.aspx?estado=");
I get an error (401).
This url returns xml feed, and, when I access it into browser, I login normally.
This user, and password are real.
Somebody have some ideia to I access it with the webclient?
Here's my guess: you're misusing the NetworkCredential constructor
The correct syntax is
public NetworkCredential(
string userName,
string password,
string domain
)
First username, then password, then domain - you got yours all wrong.
Try the following:
var client = new WebClient();
client.Credentials = new NetworkCredential("na-sebrae",
"S3br#32011", "intranet.homolog");
var html = client.DownloadData("http://www.intranet.sebrae.com.br" +
"/noticias/todas-as-notícias/rss.aspx?estado=");
I too get same error. The same link work better in browser but but giving 401 exception for WebClient.
string url = "http://www.intranet.sebrae.com.br/noticias/todas-as-notícias/rss.aspx?estado=";
var webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultCredentials;
byte[] html = webClient.DownloadData(fileAbsoluteUri);

Categories