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

让人想犯罪 __ 提交于 2019-12-01 06:13:51
Remus Rusanu

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

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