.NET WebClient sends request without authentication first

Aleksandar Stojadinovic picture Aleksandar Stojadinovic · Jun 10, 2013 · Viewed 7.3k times · Source

I'm building a web service with Asp.net web api, and I have to fetch an image from an AXIS IP Camera. The camera, however, uses Digest authentication. So my C# code looks something like this:

            WebClient webClient = new WebClient();
            webClient.UseDefaultCredentials = true;
            webClient.Credentials = new NetworkCredential("***", "***");
            byte[] imageStream = webClient.DownloadData("http://192.168.0.90/axis-cgi/jpg/image.cgi");

This all works, but when looking at Fiddler, I found that the client sends one request without authentication, and a 401 error returns. After that it sends the one with digest security.

I've found a solution with manual credentials injection here:

http://kristofmattei.be/2013/02/20/webclient-not-sending-credentials-heres-why/

But this looks wrong. It uses basic authentication, which I don't want really and looks a bit unprofessional.

Is there any way to send the signed request immediately or is this how that works because I'm noticing that the camera is returning the nonce in the first request?

Answer

argaz picture argaz · Jun 10, 2013

You can't avoid the first anonymous request because the WebClient has to figure out which authentication scheme is used, based on the 401 response he's getting, it could be basic, digest, etc... See that question.

With digest you can't avoid 2 requests anyway because the first 401 response contains a nonce (a value that is needed for the client authentication request), see Digest access authentication, Wikipedia.

If it was basic authentication you could have avoided the first request by setting the needed header manually with your credentials.