如何测试用户是否提供了正确的用户名/密码以进行基本身份验证?
我有这段代码来检索页面。如果身份验证有效,则可以正常运行
public static bool can_login(string user_name, string password)
{
WebResponse response = null;
StreamReader reader = null;
string result = null;
string login_url = "https://httpbin.org/basic-auth/user/passwd";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(login_url);
request.Method = "GET";
// Set the basic auth
string authInfo = user_name + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
response = request.GetResponse(); // Throws System.Net.WebException if login invalid
reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
return false;
}
是否有一种万无一失的方法来测试正确性,还是我应该抓住异常并希望它的凭据?