I need to send a HttpWebRequest to a url with basic inline credentials as follows:
http://user:password@doamin/query
I've tried setting the Url as is, but it didnt seem to pass the credentials (got 403).
Tried setting the Credentials property of HttpWebRequest:
request.Credentials = new NetworkCredentials("username","pasword")
And removing them from the url (resulting in http://domain/query
) but still got the same result (403).
Using the Url directly from any browser succeeded so the credentials are Ok.
What am I missing?
[UPDATE - ANSWER]
Here's the code that worked for me:
string credentials = "username:password";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(formattedUrl);
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
First you create your creds class:
NetworkCredential myCred = new NetworkCredential("username", "password");
Add it your Creds Cache:
CredentialCache credsCache = new CredentialCache();
// NOTE! THE PROTOCOL is needed in Uri (e.g. http://)
credsCache.Add(new Uri("proto://www.foo.com"), "Basic", myCred);
Now you can do a web request:
WebRequest wr = WebRequest.Create("www.foo.com");
Then set the wr.Credentials to the credsCache:
wr.Credentials = credsCache;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With