views:

1948

answers:

2

I'm trying to use HttpWebRequest to get an https URI that requires a username and password. If I put the URI into a browser it pops up a dialog asking for credentials and then works. Using HttpWebRequest gives me a 401 Unauthorized error.

The documentation for NetworkCredentials says it doesn't support SSL, but I can't find what I'm supposed to use.

Thanks, Nick

+1  A: 

Is the server using HTTP basic authentication or some other kind? If it's using HTTP basic then you can set the Credentials property on the web request to a credential containing the correct username and password, and set the PreAuthenticate property to true.

Here's an example (it's untested, so use it as a guideline only):

var uri = new Uri("https://somesite.com/something");
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = new NetworkCredential("myUserName","myPassword");
request.PreAuthenticate = true;

var response = request.GetResponse();

Note: In my experience doing this, there is some odd behavior in the .NET framework. You'd think it should do what the code says, but it actually does this:

  • Send request to server with no credentials
  • Server responds with 401
  • Re-Send request with the credentials you gave it
  • Server accepts request.

I have no idea why it would do this, as it seems broken, so perhaps it was a quirk of my machine and maybe it won't happen to you.

If your app is not performance sensitive, and your requests aren't POSTS of large data, you probably won't notice, but to get around it, I had to manually build the HTTP basic authentication header and set it on the HttpWebRequest manually by manipulating the Headers collection.

Orion Edwards
I believe the behavior you describe is the same behavior that wget in *nix shows. It's tries once and fails and then send the credentials and succeeds.
Stephan
A: 

I'm trying to do the same thing, except, I need to pass User, password, and a third field code... It seems the Basic Auth only allows for User and Password,

Any HELP?

Jeff