title: Does .NET HttpWebRequest Basic Auth / PreAuthenticate handle realm values?
body: <p>I'm trying to call into a server that serves different <a href="https://stackoverflow.com/questions/12701085/what-is-the-realm-in-basic-authentication">realm values for Basic Auth</a> when accessing different sub-urls.</p>
  
  <p>The client code I had so far didn't have to handle this, it just set credentials, set the <code>request.PreAuthenticate = true;</code> and everything worked fine for the communication:</p>
  
  <pre><code>    var request = (HttpWebRequest)WebRequest.Create("http://localhost:8877/" + suburl);
      request.Method = WebRequestMethods.Http.Get;
      request.Credentials = new System.Net.NetworkCredential("User", "Pass");
      request.CookieContainer = cookies;
      request.PreAuthenticate = true;
  
  
          using (var response = request.GetResponse())
          {
              UseResponse(response);
          }
  </code></pre>
  
  <p>This automagically handles the inital 401 response and then transfers the credentials on each subsequent request.</p>
  
  <p>What I do need to do now would be to somehow provide credentials based on the <code>realm</code> value that is returned in the <code>401 / WWW-Authenticate:</code> header.</p>
  
  <p>Is there any built-in support for this in these classes or in the version using a <a href="https://msdn.microsoft.com/en-us/library/system.net.credentialcache(v=vs.110).aspx" rel="nofollow noreferrer"><code>CredentialsCache</code></a>? The <a href="https://msdn.microsoft.com/en-us/library/system.net.networkcredential(v=vs.110).aspx" rel="nofollow noreferrer"><code>NetworkCredential</code></a> class only has user, pass, and domain properties.</p>
  
  <p>The main problem I'm having with <code>PreAuthenticate</code> is that it is unclear what it is caching the credentials for - currently, from what I can see, I <em>assume</em> that it caches the credentials once per root URL (the Uri key of the <code>CredentialCache</code>), so there's no way <code>realm</code> can work with this, but maybe I'm misunderstanding something here ...</p>