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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With