why is use of "new NetworkCredential(username, password)" not working for Basic Authentication to my website (from a WinForms C# app)?

36,554

Solution 1

WebRequest does not send credentials unless challenged by the site. The site should first respond with 401 'Authorization Required' with an WWW-Authenticate header; the WebRequest will respond to the challenge with credentials, and the service should respond with the 200 Http content.

Sounds like the site does not implement Basic auth properly (the spec says it should challenge first, to pass in the realm) which is a very common behavior. You can add the Basic authentication manually to the WebRequest.Headers collection, which is what most developers end doing anyway.

See HttpWebRequest not passing Credentials

Solution 2

If someone is looking for the server side fix then just add

HttpContext.Response.Headers.Add("WWW-Authenticate", "Basic realm=\"MyRealm\"");

after you set the StatusCode = 401

Share:
36,554
Greg
Author by

Greg

Updated on May 19, 2020

Comments

  • Greg
    Greg almost 4 years

    I have a website that uses Basic Authentication (username/password).

    Why is the following code not working? When I run it the web application takes me to the login controller, whereas I'm expecting that it should already be authenticated given I'm populating the credentials. In other words I'm trying to confirm how, in .NET, I confirm my winforms HttpWebRequest so that it will automate the authentication process. I'm assumeing that NetworkCredential is the .net class that should do this? Or in .NET is there an expectation there is some manual two step process you have to implement yourself?

    Here is the code:

        // Create a new webrequest to the mentioned URL.            
        var uri = new Uri("http://10.1.1.102:3000/download/sunset");
        var myWebRequest = (HttpWebRequest)WebRequest.Create(uri);            
        myWebRequest.PreAuthenticate=true;            
        var networkCredential=new NetworkCredential("test", "asdfasdf");                        
        myWebRequest.Credentials=networkCredential;
        var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
    
        Console.Out.WriteLine("STATUS = " + myWebResponse.StatusCode);
    
        var stream = myWebResponse.GetResponseStream();
        var reader = new StreamReader(stream);
        string text_read = reader.ReadToEnd();
        Console.WriteLine(text_read);
        DisplayHtml(text_read);
        reader.Close();
        stream.Close();
        myWebResponse.Close();
    

    Thanks