C#WebClient HTTP基本身份验证失败401具有正确的凭据

时间:2015-02-19 19:18:19

标签: c# http-post webclient basic-authentication http-status-code-401

我正在尝试通过 自动配置无线路由器的SSID和密码。路由器没有我所知道的API。这是一个无品牌的中国路由器。 Web配置似乎是配置的唯一选项。它使用(您浏览到路由器的IP地址并获得一个通用对话框,询问用户名和密码)。

当我手动更新SSID和密码(两个单独的表单)时,我使用Wireshark来获取请求使用的标题和表单字段。然后,我尝试使用来模拟这些次请求。

以下是我用来尝试保存新SSID的代码片段(NameValueCollection在别处定义):

private const string FORM_SSID = "http://192.168.1.2/formWlanSetup.htm";
private const string REF_SSID = "http://192.168.1.2/formRedirect.htm?redirect-url=wlbasic.htm&wlan_id=0";
private NameValueCollection mFields = HttpUtility.ParseQueryString(string.Empty, Encoding.ASCII);

public string SaveConfigResponse()
{
    try
    {
        using (WebClient wc = new WebClient())
        {
            wc.Headers[HttpRequestHeader.Accept] = "text/html, application/xhtml+xml, */*";
            wc.Headers[HttpRequestHeader.Referer] = REF_SSID;
            wc.Headers[HttpRequestHeader.AcceptLanguage] = "en-US";
            wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            wc.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            wc.Headers[HttpRequestHeader.Host] = "192.168.1.2";
            wc.Headers[HttpRequestHeader.Connection] = "Keep-Alive";
            wc.Headers[HttpRequestHeader.ContentLength] = Encoding.ASCII.GetBytes(mFields.ToString()).Length.ToString();
            wc.Headers[HttpRequestHeader.CacheControl] = "no-cache";
            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(config_user + ":" + config_pass));
            wc.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
            //wc.Credentials = new NetworkCredential("admin", "admin");
            return Encoding.ASCII.GetString(wc.UploadValues(FORM_SSID, "POST", mFields));
        }
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

这导致未经授权的响应。我试图做的事情是不可能的吗?


更新

以下是浏览器帖子/响应和WebClient帖子/响应的HTTP标头。再一次,我尝试将我看到的浏览器发布内容与我的WebClient帖子相匹配。

浏览器:

POST /formWlanSetup.htm HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://192.168.1.2/formRedirect.htm?redirect-url=wlbasic.htm&wlan_id=0
Accept-Language: en-US
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: 192.168.1.2
Content-Length: 524
Connection: Keep-Alive
Cache-Control: no-cache
Authorization: Basic YWRtaW46YWRtaW4=

HTTP/1.1 302 Found
Location: wlbasic.htm
Content-Length: 183
Date: Thu, 23 Oct 2014 18:18:27 GMT
Server: eCos Embedded Web Server
Connection: close
Content-Type: text/html
Transfer-Encoding: chunked
Cache-Control: no-cache

Web客户端:

POST /formWlanSetup.htm HTTP/1.1
Accept-Language: en-US
Accept-Encoding: gzip, deflate
Cache-Control: no-cache
Authorization: Basic YWRtaW46YWRtaW4=
Accept: text/html, application/xhtml+xml, */*
Content-Type: application/x-www-form-urlencoded
Referer: http://192.168.1.2/formRedirect.htm?redirect-url=wlbasic.htm&wlan_id=0
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: 192.168.1.2
Content-Length: 524
Connection: Keep-Alive

HTTP/1.1 401 Not Authorized
WWW-Authenticate: Basic realm="AP"
Date: Thu, 23 Oct 2014 18:18:41 GMT
Server: eCos Embedded Web Server
Connection: close
Content-Type: text/html
Transfer-Encoding: chunked
Cache-Control: no-cache

再次,这一切都是从Wireshark收集的。我对Wireshark不太熟悉,但我能够做到这一点。如果我知道如何正确提取原始数据包数据并粘贴它,我会的。

重要的新观察

  • Wireshark捕获来自浏览器和WebClient的后期数据包显然在标题的顺序上有所不同。不过,我不知道可能会有多么重要,因为每个标题的数据显然是相同的。
  • 我注意到的数据包之间的一个明显区别是,Wireshark报告的浏览器数据包明显大于WebClient数据包。看一下逐项观点,我找不到任何明显的差异。我假设发布用于比较的原始数据会显示很多,但同样,我真的不知道该怎么做。
  • 我有一个令人眼花缭乱的启示。 尽管回复清楚地说明'(401)未经授权',但邮件实际上已被路由器接受了!在我的WebClient帖子显示已接受并保存设置后,进入路由器的Web配置。

最后一个是个大人物。我发现自己处于这样一种情况,我可以使用WebClient帖子来保存我的配置,但我必须忽略401响应才能这样做。显然,这远非理想。如此接近,但到目前为止!


最终更新(决议)

我已经解决了基本身份验证失败的问题,但不是WebClient。我使用了@caesay的建议并与HttpWebRequest一起(与WebResponse一起)。我的表单帖子导致重定向,所以我不得不允许。

这基本上就是我的用途:

private bool ConfigureRouter()
{
    bool passed = false;
    string response = "";
    HttpWebRequest WEBREQ = null;
    WebResponse WEBRESP = null;            

    // Attempt to POST form to router that saves a new SSID.
    try
    {
        var uri = new Uri(FORM_SSID); // Create URI from URL string.
        WEBREQ = HttpWebRequest.Create(uri) as HttpWebRequest;

        // If POST will result in redirects, you won't see an "OK"
        // response if you don't allow those redirects
        WEBREQ.AllowAutoRedirect = true;

        // Basic authentication will first send the request without 
        // creds.  This is protocol standard.
        // When the server replies with 401, the HttpWebRequest will
        // automatically send the request again with the creds when
        // when PreAuthenticate is set.
        WEBREQ.PreAuthenticate = true;
        WEBREQ.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;

        // Mimic all headers known to satisfy the request
        // as discovered with a tool like Wireshark or Fiddler
        // when the form was submitted from a browser.
        WEBREQ.Method = "POST";
        WEBREQ.Accept = "text/html, application/xhtml+xml, */*";
        WEBREQ.Headers.Add("Accept-Language", "en-US"); // No AcceptLanguage property built-in to HttpWebRequest
        WEBREQ.UserAgent = USER_AGENT;
        WEBREQ.Referer = REF_SSID;
        WEBREQ.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        WEBREQ.KeepAlive = true;
        WEBREQ.Headers.Add("Pragma", "no-cache"); // No Pragma property built-in to HttpWebRequest

        // Use a cached credential so that the creds are properly
        // submitted with subsequent redirect requests.
        CredentialCache creds = new CredentialCache();
        creds.Add(uri, "Basic", new NetworkCredential(config_user, config_pass));
        WEBREQ.Credentials = creds;

        // Submit the form.
        using (Stream stream = WEBREQ.GetRequestStream())
        {
            SSID ssid = new SSID(ssid_scanned); // Gets predefined form fields with new SSID inserted (NameValueCollection PostData)
            stream.Write(ssid.PostData, 0, ssid.PostData.Length);
        }

        // Get the response from the final redirect.
        WEBRESP = WEBREQ.GetResponse();
        response = ((HttpWebResponse)WEBRESP).StatusCode.ToString();
        if (response == "OK")
        {
            StatusUpdate("STATUS: SSID save was successful.");
            passed = true;
        }
        else
        {
            StatusUpdate("FAILED: SSID save was unsuccessful.");
            passed = false;
        }
        WEBRESP.Close();
    }
    catch (Exception ex)
    {
        StatusUpdate("ERROR: " + ex.Message);
        return false;
    }
    return passed;
}

1 个答案:

答案 0 :(得分:1)

  

我试图做的只是不可能吗?

不,这不是不可能的。多年来我一直有很多关于网络抓取的麻烦,因为有些网络服务器很挑剔,你的路由器接口可能是一个自定义的web服务器实现,不像apache或iis那样宽容。

我会进行wireshark捕获并获取chrome发送的原始数据包数据(w / payload等),然后为您的应用程序执行相同的捕获。确保数据包与您获得的数据包相似。如果您仍有问题,请将数据包捕获发布到pastebin或其他内容,以便我们查看。

修改::

不要使用有限的WebClient API,请尝试使用一些较低级别的项目,我想知道以下代码是否适合您:

var uri = new Uri("http://192.168.1.2/formWlanSetup.htm");
var cookies = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.CookieContainer = cookies;
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
request.Referer = "http://192.168.1.2/formRedirect.htm?redirect-url=wlbasic.htm&wlan_id=0";
request.Credentials = new NetworkCredential(config_user, config_pass);
request.PreAuthenticate = true;
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
string htmlResponse = reader.ReadToEnd();