12

I want to login to a Sharepoint portal which brings up a login dialog but is using NTLM authentication. How can I modify the HTTP headers in C# to make a successful login request? I assume I would need to make a HTTPWebRequest to a page within the logged in section of the portal and post the HTTP headers collection alongside this?

Alex Angas
  • 59,219
  • 41
  • 137
  • 210
blade
  • 121
  • 1
  • 1
  • 3

3 Answers3

23

You can do this using the WebRequest class.

WebRequest req = WebRequest.Create(tokenUri);
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
WebResponse resp = req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream());
var token = reader.ReadToEnd().Trim();

This code reads the whole response into a variable called token.

John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • 11
    When trying this I get `The remote server returned an error: (401) Unauthorized`. Same URL/user/password work on Firefox. NTLM over HTTP – Nicolas Raoul Apr 04 '13 at 08:10
3

To use NTLM see John's answer. If you need to have headers across sessions look at the CookieContainer property on the HttpWebRequest object. You will need to keep a reference to your CookieContainer and attach it to any other HttpWebRequests you make.

Community
  • 1
  • 1
Matthew Whited
  • 22,160
  • 4
  • 52
  • 69
0

In order to use NTLM authentication for WebRequest cred info should be stored in CredentialCache:

var request = (HttpWebRequest)WebRequest.Create(url);
// INIT REQUEST HERE ...

var credential = new NetworkCredential(username, password, domain);
var credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "NTLM", credential);
request.Credentials = credentialCache;

// SEND ...

Source: http://predicatet.blogspot.com/2007/01/httpwebrequest-networkcredential-with.html

John Deer
  • 2,033
  • 2
  • 13
  • 16