Saturday, August 16, 2014

System.Net.CredentialCache supports Digest Auth

In my last post I talked about implementing Digest Authentication in WebAPI. That was a server side implementation, but how do you make requests to that server? Good news: .NET's built in CredentialCache supports Digest Authentication!

PreAuthenticate

Be sure to enable PreAuthenticate, otherwise each request will require a new digest token have to make an additional two requests to get it! Do not worry, the request will not send your credentials without having a token first.

PreAuthenticate = false

PreAuthenticate = true

Test Code

[Fact]
public void DigestCredentials()
{
    var requestUri = new Uri("http://localhost/DigestAuthDemo/");
 
    var credCache = new CredentialCache
    {
        {
            new Uri("http://localhost/"), 
            "Digest", 
            new NetworkCredential("UserName", "Password", "/")
        }
    };
 
    using (var clientHander = new HttpClientHandler
    {
        Credentials = credCache,
        PreAuthenticate = true
    })
    using (var httpClient = new HttpClient(clientHander))
    {
        for (var i = 0; i < 5; i++)
        {
            var responseTask = httpClient.GetAsync(requestUri);
            responseTask.Result.EnsureSuccessStatusCode();
        }
    }
}

Enjoy,
Tom

1 comment:

  1. If you’ve ever found yourself in that https://essaysrescue.com/123helpme-review/ position – the one where you feel like curling up in the foetal position and chanting “write me an essay” then you’ve come to the right place.

    ReplyDelete

Real Time Web Analytics