Digest Authentication is performed automatically, if requested by the server. You only need to set the Credentials
property on the WebClient
or HttpRequest
.
You can test it against httpbin.org
like this:
using (var client = new Rebex.Net.WebClient())
{
client.Credentials = new NetworkCredential("usr", "pwd");
var authTest = client.DownloadString("http://httpbin.org/digest-auth/auth/usr/pwd");
Console.WriteLine(authTest);
}
Unfortunately, httpbin.org
does not support POST
for digest-auth
testing. However, it would work the same way, just instead DownloadString
use the UploadString
method.
If the UploadString
method does not work with your server and you get for example 400 Bad Request.
response, your server probably requires Content-Type
header to be specified. In such case, you cannot use simple WebClient.UploadString()
method, but you need to do it using HttpRequst
API.
You can test it against reqres.in
like this:
var creator = new HttpRequestCreator();
var req = (WebRequest)creator.Create("https://reqres.in/api/login");
req.Method = "POST";
req.Headers.Add("Accept", "application/json");
req.Headers.Add("Content-Type", "application/json");
req.Credentials = new NetworkCredential("eve.holt", "pwd");
using (var upload = new StreamWriter(req.GetRequestStream()))
{
var data = @"{""email"": ""eve.holt@reqres.in"", ""password"": ""pwd""}";
upload.Write(data);
}
var res = req.GetResponse();
using (var download = new StreamReader(res.GetResponseStream()))
{
var response = download.ReadToEnd();
Console.WriteLine(response);
}