I have an HttpWebRequest with Credentials, as seen below. This works perfectly well. However, something strange happens when I change my password on the server side: subsequent requests to the same URL are successful, even though the password is no longer valid.
This behavior continues even if I close the app completely and reopen it. Do the Credentials persist somehow? Any insight would be greatly appreciated.
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(item.Url) as HttpWebRequest;
nc = new NetworkCredential();
nc.UserName = Username;
nc.Password = Password;
request.Credentials = nc;
request.BeginGetResponse(new AsyncCallback(SubReadWebRequestCallback), request);
}
Related
I am using console app to access WebApi.
I am creating WebRequest as follows:
var request = (HttpWebRequest)WebRequest.Create(url);
if (username == String.Empty)
{
request.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else
{
request.Credentials = new NetworkCredential(username, password);
}
I am opening command window using:
runas /savecred /user:test_user cmd
The problem is, if a username and password is supplied, the app is still connecting as "test_user" and ignores supplied username and password.
My question is: How can I make WebRequest to use the supplied username and password?
It might be that the parameter savecred is saving the credentials. Try running this:
rundll32.exe keymgr.dll, KRShowKeyMgr
and remove "test_user". Then run your program again without savecred.
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.
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);
I'm trying coding some functionality where the user may log in into a remote server by using its own Windows Credentials or by specifying some user, password and domain.
In order to know how to do it I read this link[1].
I have been able to successfully log in via CredentialCache.DefaultCredentials.
However, whenever I try to authenticate via user, name, password and domain I keep on getting a 401 error.
After some Googling and searching here I have found some probable errors (redirecting, different auth. types {basic, digest, ntlm, negotiate} and even the case contrary [i.e. being able to login through user+pasword but no by CredentialCache.DefaultCredentials]).
Any hints?
Edit: maybe some code would give you some clues about what I am doing wrong.
static void Main(string[] args)
{
string password = "password", username = "Username", dom = "DOMAIN";
string url = "http://my.url.com/LoginWithNativeCredentials?";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
/////// Different User code////
NetworkCredential credentials = new NetworkCredential(username, password, dom);
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(url), "NTLM", credentials);
request.Credentials = cache;
/////////////////////////
////// Current Windows user's credential
//request.Credentials = CredentialCache.DefaultCredentials;
/////////////////////////
request.AllowAutoRedirect = true;
request.CookieContainer = new CookieContainer(5);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine("In!");
}
Console.WriteLine("Done!");
Console.ReadLine();
}
Many thanks!
[1] http://support.microsoft.com/kb/811318
For the project I'm working on, we have a desktop program that contacts an online server for a store. Because it's used in schools, getting the proxy setup right is tricky. What we've gone for is to allow users to specify proxy details to use if they want, otherwise it uses the ones from IE. We've also tried to bypass incorrect details being put in, so the code tries the user specified proxy, if that fails the default one, if that fails, then with credentials, if that fails then null.
The problem I'm having is that in places where the proxy settings need to be changed in succession (for example, if their registration fails because the proxy is wrong, they change one tiny thing and try again, takes seconds.) I end up with calls to a HttpRequests .GetResponse() timing out, causing the program to freeze for a good while. Sometimes if I leave a minute or two between the changes, it doesn't freeze, but not every time (Just tried again now after 10mins and it's timing out again).
I can't spot anything in the code that could cause this - though it looks a bit messy. I don't think it could be the server refusing the request unless it's generic server behaviour as I've tried this with requests to our server and others such as google.co.uk.
I'm posting the code in the hope that someone may be able to spot something that's wrong with it, or knows a much simpler way of doing what we're trying to.
The tests we run are without any proxy, so the first part is usually skipped. The first time ApplyProxy is run, it works fine and finishes everything in the first try block, the second, it can either timeout on the GetResponse in the first try block and then go through the rest of the code, or it can work there and timeout on the actual requests made for the registration.
Code:
void ApplyProxy()
{
Boolean ProxySuccess = true;
String WebRequestURI = #"http://www.google.co.uk";
if (UseProxy)
{
try
{
String ProxyUrl = (ProxyUri.ToLower().Contains("http://")) ?
ProxyUri :
"http://" + ProxyUri;
WebRequest.DefaultWebProxy = new WebProxy(ProxyUrl);
if (!string.IsNullOrEmpty(ProxyUsername) && !string.IsNullOrEmpty(ProxyPassword))
WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(ProxyUsername, ProxyPassword);
HttpWebRequest request = HttpWebRequest.Create(WebRequestURI) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
}
catch
{
ProxySuccess = false;
}
}
if(!ProxySuccess || !UseProxy)
{
try
{
WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
HttpWebRequest request = HttpWebRequest.Create(WebRequestURI) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
}
catch (Exception e)
{ //try with credentials
//make a new proxy from defaults
WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
String newProxyURI = WebRequest.DefaultWebProxy.GetProxy(new Uri(WebRequestURI)).ToString();
if (newProxyURI == String.Empty)
{ //check we actually get a result
WebRequest.DefaultWebProxy = null;
return;
}
//continue
WebProxy NewProxy = new WebProxy(newProxyURI);
NewProxy.UseDefaultCredentials = true;
NewProxy.Credentials = CredentialCache.DefaultCredentials;
WebRequest.DefaultWebProxy = NewProxy;
try
{
HttpWebRequest request = HttpWebRequest.Create(WebRequestURI) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
}
catch
{
WebRequest.DefaultWebProxy = null;
}
}
}
}
Is it not just a case of needing to set the Timeout property of the HttpWebRequest? It could be that the connection is being made, but not serviced (wrong type of proxy server or stalled server, for example), in which case it may be that the request is waiting for the Timeout period before giving up — a shorter timeout may be preferrable here.
Seems to be a programming error on my behalf. The requests were left open and obviously either the program or the server doesn't like this. Simply closing the HttpWebRequests once done seems to remove this issue.