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

天大地大妈咪最大 提交于 2019-12-01 04:24:21

问题


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


回答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




回答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



来源:https://stackoverflow.com/questions/1829609/why-is-use-of-new-networkcredentialusername-password-not-working-for-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!