Create a HttpWebRequest for a http://user:password

2019-04-07 05:27发布

问题:

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

回答1:

First you create your creds class:

NetworkCredential myCred = new NetworkCredential("username", "password");

Add it your Creds Cache:

CredentialCache credsCache = new CredentialCache();

credsCache.Add(new Uri("www.foo.com"), "Basic", myCred);

WebRequest wr = WebRequest.Create("www.foo.com");
wr.Credentials = credsCache;

Then set the wr.Credentials to the credsCache



回答2:

Plain text password is no longer a valid part of URL (according to respective RFC). You should be using NetworkCredentials as you already tried. See MSDN for code snippet/sample:

NetworkCredential myCred = new NetworkCredential(
    SecurelyStoredUserName,SecurelyStoredPassword,SecurelyStoredDomain);

CredentialCache myCache = new CredentialCache();

myCache.Add(new Uri("http://www.contoso.com"), "Basic", myCred);
myCache.Add(new Uri("http://app.contoso.com"), "Basic", myCred);

WebRequest wr = WebRequest.Create("http://www.contoso.com");
wr.Credentials = myCache;

UPD. Compared to MSDN code snippet, one needs to prefix strings with "http://" to avoid "Invalid URI" exception.