Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticated HttpWebRequest with redirection, persisting credentials?

My ASP.NET 2.0 app creates a HTTPWebRequest to a site within a company's intranet, which uses NTLM authentication. The credentials passed are for a service account, which is authenticated on the domain successfully (the security log confirms this)

Some abbreviated code follows..

HttpWebRequest req = WebRequest.Create(queryUrl) as HttpWebRequest;
NetworkCredential cred = new NetworkCredential(username,
                pwd, domain); 
req.Credentials = cred;

HttpWebResponse response = req.GetResponse() as HttpWebResponse;

As part of the request, there are a couple of redirections (within the same domain) to the final response - which is handled OK on my dev machine (Windows 2k)

When this request is created from my deployment environment (Windows 2k3), I get a 401 Unauthorized error returned from the site, seemingly after the first redirect code is returned (301 Moved), and my request object attempts to follow the redirect.

So basically, does anyone know of any issues surrounding authenticated HttpWebRequests that follow redirections?

PS - The obvious workaround is to simply request the page redirected to - but I the admins in charge of the intranet site want to monitor my app's usage by redirecting me through a specific page.

like image 888
Phil Jenkins Avatar asked May 29 '09 14:05

Phil Jenkins


2 Answers

For HttpWebRequest to reuse credentials across redirects you need to use a credential cache. If you just assign a NetworkCredentials object it will only be used on the first request.

Here is an example:

HttpWebRequest req = WebRequest.Create(queryUrl) as HttpWebRequest;
NetworkCredential cred = new NetworkCredential(username, pwd, domain); 
var cache = new CredentialCache {{queryUrl, "Ntlm", cred}};
req.Credentials = cache;
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
like image 93
Jared Kells Avatar answered Sep 21 '22 02:09

Jared Kells


It's going to depend on how your auth. scheme works. The Network credentials is only going to help for the NTLM part of if. I suspect that the site you are trying to access is using forms authentication also. If this is the case, when you log in you should get an auth cookie, you will need to include that in subsequent requests, e.g. after a redirect. I think the WebRequest object has a headers collection that you can use to hold the cookie. Might be a good idea to use fiddler or firebug to see what is coming across when you normally browse.

like image 37
Rob Avatar answered Sep 23 '22 02:09

Rob