title: Manual Windows Authentication
body: <p>I'm currently trying to figure out how to perform manual windows authentication in our ASP.NET Application. The problem is that we have an OData service running, and use FormsAuthentication to provide the generic login mechanism and allow the PUT &amp; DELETE verbs for OData, including form redirects.</p>
  
  <p>However, for some customers we have integrated Windows Authentication to allow smooth integration for their users with the active directory. The problem now is that we want to be able to switch authentication methods without breaking the Odata service, because we depend on it.</p>
  
  <p>What we're trying to do is mimic the Windows Authentication mechanics using an IhttpModule. So far we're able to toggle the feature on &amp; off, and we get the challenge when a request is made. What I don't know is how to use the received information from the browser to perform authentication against the active directory:</p>
  
  <p>This is the code we use to extract the NTLM information from the current request:</p>
  
  <pre><code>/// &lt;summary&gt;
  /// &lt;para&gt;Determines whether the current &lt;see cref="HttpRequest"/&gt; is a NTML challenge.&lt;/para&gt;
  /// &lt;/summary&gt;
  /// &lt;param name="request"&gt;The &lt;see cref="HttpRequest"/&gt; to evaluate.&lt;/param&gt;
  /// &lt;param name="header"&gt;The output header to authenticate.&lt;/param&gt;
  /// &lt;returns&gt;True if the current &lt;see cref="HttpRequest"/&gt; is considered a NTML challenge.&lt;/returns&gt;
   protected bool IsNtlmChallenge(HttpRequest request, out string header)
   {
        const string headerName = @"Authorization";
        if (request.Headers.AllKeys.Contains(headerName))
        {
             header = request.Headers[headerName];
             return true;
        }
  
        header = string.Empty;
        return false;
   }
  </code></pre>
  
  <p>This allows us to extract the header from the request. What I need to know now is how I perform the authentication with this on the active directory.</p>
  
  <p>This is the logic we use to extract the info:</p>
  
  <pre><code>// Check if we need to handle authentication through Windows authentication or not.
  if (WindowsAuthentication)
  {
      string encryptedHeader;
  
      // If this is a challenge from the client, perform the Windows Authentication using the 
      // information stored inside the header.
      if(IsNtlmChallenge(HttpContext.Current.Request, out encryptedHeader))
      {
           /* how to authenticate here with the encrypted header? */
      }
  
      HttpContext.Current.Response.AddHeader("WWW-Authenticate", "NTLM");
      HttpContext.Current.Response.StatusCode = 401;
      return;
  }
  </code></pre>
  
  <p>Hope someone can provide the anwser that I need.</p>