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

No comments:

Post a Comment

Real Time Web Analytics