HttpWebRequest DefaultNetworkCredentials give error 401

Jerry Lam picture Jerry Lam · Jul 30, 2013 · Viewed 7.4k times · Source

Im trying to request a url that require windows authentication using HttpWebRequest, I was using

request.Credential = New NetworkCredential("username", "password");

everything was working find until I decide not to hardcord the username and password, and switch to

request.Credential = CredentialCache.DefaultNetworkCredentials;

then i got 401 unauthenticated error. I checked my user with

WindowsIdentity.GetCurrent();

It returns my username correctly, but the

CredentialCache.DefaultNetworkCredentials;

return me empty string for username, domain... pretty much everything is empty string.. Too bad that the HttpWebRequest.Credential is expecting ICredential means i can't set WindowsIdentity.GetCurrent() to it.

Is there anyway that i could pass my current login user to the HttpWebRequest.Credential??

Is CredentialCache.DefaultNetworkCredentials; the correct way? or im just missing some settings?

I had read through some artical like this one http://msdn.microsoft.com/en-us/library/ms998351.aspx.

It is either too long and too complicated for me to understand or it doesn't work. Im new to this, hope to get some straight foward answer here.

Answer

Kai Hartmann picture Kai Hartmann · Jul 30, 2013

If you are using basic authentication, then this will not work. See this question: HttpWebRequest with basic authentication fails with 401 erorr for DefaultNetworkCredentials

And this microsoft article states, that DefaultCredentials just apply to NTLM, negotiate, and Kerberos-based authentication. http://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultcredentials.aspx

For information purposes this is an article explaining the authentication methods in short: http://msdn.microsoft.com/en-us/library/ms789031.aspx