Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HttpWebRequest.Credentials Property for Basic Authentication?

How can I use the Webrequest Credentials Property to send an basic authentication header? Why isn't the Authorization header send with the request even whenPreAuthenticate is set to true?

WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");
request.Credentials = new NetworkCredential("githubUsername", "githubPassword");
request.PreAuthenticate = true;
var response = request.GetResponse();
like image 566
Jos Vinke Avatar asked Dec 16 '22 04:12

Jos Vinke


1 Answers

I've done some additional research based on Måns Tånneryd`s answer. And the link he posted in his comment: PreAuthenticate Property of WebRequest - Problem.

First of all as described in his link the HttpWebRequest.PreAuthenticate Property does NOT send the Authentication header PRE authentication, but pre sends it in following requests, after Authentication. From MSDN:

true to send an HTTP Authorization header with requests after authentication has taken place; otherwise, false. The default is false.

So even with the PreAuthenticate property set to true, we still need an WWW-Authenticate challenge with a 401 Unauthorized before anything happens. Now if we try to authenticate against github with the following code:

WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");
request.Credentials = new NetworkCredential("githubUsername", "githubPassword");

var response = request.GetResponse();

An WebException will be thrown, because we don't get a WWW-Authenticate challenge. If we capture this in Fiddler we will get the following:

enter image description here

However if we try this, with the exact same code, against a website that does return a WWW-Authenticate challenge we will see the following in Fiddler:

enter image description hereenter image description here

And the response will have the result as expected.

like image 90
Jos Vinke Avatar answered May 09 '23 19:05

Jos Vinke