Why am I getting 401 Unauthorized when I create an HttpWebRequest with the correct credentials?

I have a url and username and password for an external site. If I get the URL through the browser, an authentication window appears. I give him a username and password, and I can get to the page.

I am trying to do the same with code using the HttpWebRequest object:

var webRequest = (HttpWebRequest)WebRequest.Create(url); 

webRequest.GetResponse() , etc.

This worked before website owners added some protection to the site and provided me with a username and password. WebRequest has a credentials property, which I set as follows:

 webRequest.Credentials = new NetworkCredential("username", "password") 

I also tried:

 webRequest.Credentials = new NetworkCredential("username", "password", "url domain") 

this always results in an error:

"The remote server returned an error: (401) Unauthorized."

Am I missing something obvious?

+4
source share
5 answers

Using System.Net.NetworkCredential may be ineffective depending on the resource authentication model. It would be helpful to understand the model used by the remote site.

OpenID, form authentication, and integrated Windows authentication work differently. You can try to determine which authentication method they use using the tools described as @Christoph and @Lex, or simply contact your remote website provider.

If the remote site uses a negotiation protocol such as Kerberos or NTLM, then the behavior you experience is really strange; however, some other protocols may require you differently.

+1
source

try debugging your request with a violinist (www.fiddler2.com).

Therefore, you must run Fiddler and add proxy settings to your request:

 webRequest.Proxy = New WebProxy("http://127.0.0.1:8888") 
0
source

If you use HTTP, simply use Microsoft Network Monitor or Wireshark to record which 401 message is being returned from the web server. It can be 401.3 or another error code, which has actually a different meaning.

0
source

If you do not have privacy, you can send the URL to which you are trying to access.

If the URL is incorrect or refers to an invalid page (or an incorrect combination of pages + parameters), you will sometimes see server errors like this.

I was working with a legacy web application from the state of Michigan, and every time I tried to access a page with incorrect page parameters, it threw 400 style errors.

0
source

Do you use query filtering on the web server? Can you check the different verbs that are set up for refusal?

0
source

Source: https://habr.com/ru/post/1316525/


All Articles