28

I'm trying to get a HTML source of a website through C# code. When I access the site with Windows Authentication, the following code works:

using (WebClient client = new WebClient())
            {
                client.Credentials = CredentialCache.DefaultCredentials;
                using (Stream stream = client.OpenRead("http://intranet/"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    MessageBox.Show(reader.ReadToEnd());
                }
            }

When I enter my domain credentials manually, I get an "unauthenticated" message.

using (WebClient client = new WebClient())
            {
                NetworkCredential credentials = new NetworkCredential("username", "pass", "domain");
                client.Credentials = credentials;
                using (Stream stream = client.OpenRead("http://intranet/"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    MessageBox.Show(reader.ReadToEnd());
                }
            }

Why is it so?

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
agnieszka
  • 14,897
  • 30
  • 95
  • 113

1 Answers1

56

Try this:

CredentialCache cc = new CredentialCache();
cc.Add(
    new Uri("http://intranet/"), 
    "NTLM", 
    new NetworkCredential("username", "pass", "domain"));
client.Credentials = cc;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 11
    You need to specify the authentication type. When the server challenges the client with NTLM authentication the ICredentials.GetCredential method will be called on WebClient.Credentials with `authType = "NTLM"`. If you used `WebClient.Credential = new NetworkCredential(...)` as no authentication type is specified the client won't be able to respond correctly. `CredentialCache` already implements this functionality. – Darin Dimitrov Nov 05 '09 at 14:57
  • 1
    What should I specify in Uri? Resource I am trying to get is "https://myDomain.com/images/userName". Can you put any live example how Uri and NetworkCredentials should look like? Thx – Krzysztof Morcinek Mar 07 '14 at 09:09
  • 8
    Good answear, and I´d like to point out that if you don´t want to create a new NetworkCredential you can get the default ones from DefaultNetworkCredentials: `NetworkCredential networkCredential = CredentialCache.DefaultNetworkCredentials.GetCredential(uri, "NTLM")` – Jonas Jakobsson Jan 22 '16 at 09:10
  • I don't believe that this technique will work if the client app is running on IIS 8.5 - at least I could not get this working there. Works OK on an IIS 7.5 instance – PBMe_HikeIt Jan 26 '18 at 21:49
  • This is not working for me .. I am using Windows authentication and tried to use this for it... Even the post says windows authentication … – Ziggler Feb 07 '19 at 18:39