HttpWebRequest 401 error

1.2k views Asked by At

I am developing an intranet application (Windows Authentication) which download report stream from reporting server then save it as a file. When I ran it in debuging mode it works fine。 The code is as below:

       HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

       req.UseDefaultCredentials = true; 

        HttpWebResponse response = (HttpWebResponse)req.GetResponse();
        Stream fStream = response.GetResponseStream();

However after I deployed it to the server, it won't get response rather than getting 401 unauthorized error.

Even I change the code to: HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

        string domain = ConfigurationManager.AppSettings["SchedulerDomain"];
        string userName = ConfigurationManager.AppSettings["SchedulerUser"];
        string passWord = ConfigurationManager.AppSettings["SchedulerPassword"];
        NetworkCredential credential = new System.Net.NetworkCredential(userName, passWord, domain);
        req.Credentials = credential;

         HttpWebResponse response = (HttpWebResponse)req.GetResponse();
        Stream fStream = response.GetResponseStream();

Get the same error. The user setup in the code has the permission to view/run the report.

The IIS7 is using Negotiate and NTLM. (Due to complicated reason, can't change Kerberos), run under ApplicationPoolIdentity

My question is, when I run it under debug mode, the user is my windows account, but why it fails when I tried to send the credential to the reporting server?

Anyone can help?

2

There are 2 answers

0
Jim Yu On

I capture all the request from the application server to the reporting server, find that all the requests' header's credential username and domain, password are null. Finally I think it is the NTLM causes the issue as here requires two credential hops which NTLM can't handle it, need use Kerberos.

There is another solution if you can't use Kerberos authentication: disable the asp.net impersonation, so from the app server to reporting server will use the applicationpoolidentity, which is a local machine account with account as such: domain/machinename$. So if you grant this account with browse permission on the reporting server, it should work.

0
usr4896260 On

I'm not sure how your IIS is configured but it seems like the Identity in your Application Pools setting for your app is overriding any supplied credential. Most obviously, the user that it is trying to authenticate with does not have access. That being said go to your IIS Manager and check the Identity settings for the site's Application Pool.

enter image description here

Change it to a user that has access to the report viewer and that should fix it. I've had a similar issue I posted here in case anyone is interested.