简体   繁体   中英

Why Am I Getting 401 Unauthorized Response?

I have the following C# code I'm trying to use to get a response from a url I can go to manually.

        static void Main(string[] args)
        {
            Uri theRequestUriString = new Uri("<<<my_url>>>");
            var request = WebRequest.Create(theRequestUriString);
            request.UseDefaultCredentials = true;
            WebProxy myproxy = new WebProxy("<<<my_proxy>>>:<<<my_port>>>", true);
            request.Proxy = myproxy;
            request.Timeout = Convert.ToInt32(TimeSpan.FromMinutes(5).TotalMilliseconds);
            request.Credentials = CredentialCache.DefaultCredentials;

            string textResponse;
            var resp = request.GetResponse();//*****401 error here*****
            using (var sr = new StreamReader(resp.GetResponseStream()))
            {
                textResponse = sr.ReadToEnd().Trim();
            }

        }
System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.'

I can go there manually but get a 401 Unauthorized if I try to use this code. Shouldn't the CredentialCache take care of that? I'm using Visual Studio locally if that is not the case.

If the url is instead https://www.yahoo.com then this works just fine.

In your code

request.Credentials = CredentialCache.DefaultCredentials

means you are using NTLM for auth .

Windows authentication (formerly named NTLM, and also referred to as Windows NT Challenge/Response authentication) is a secure form of authentication because the user name and password are hashed before being sent across the network. When you enable Windows authentication, the client browser sends a strongly hashed version of the password in a cryptographic exchange with your Web server.

Read more here

This is basically your windows credentials. When one opens the website in the browser they are able to easily authenticate with the website using their windows credentials which is passed on to the website.

Now in regards to why it is not working when you run your code. The place where I would see is whether you are setting your content to use windows auth or not. There are several ways of doing it and some of them are here

I will also point you to this SO Answer: Windows authentication doesn't work when I run project from Visual Studio

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM