C#Http基本身份验证绕过

时间:2011-11-22 14:26:52

标签: c# httpwebrequest basic-authentication

在C#ASP.NET应用程序上,我设法绕过基本身份验证(通过HTTPWebRequest上的“Authorization”标头发送用户名/密码),我终于解锁了受htaccess保护的目标页面(位于不同的服务器上,基本身份验证)并将流发送回浏览器。

只要用户点击链接,就会出现此问题,再次弹出基本身份验证登录框。我们不希望用户再次输入用户名/密码。

似乎我需要在标题中发回一些东西告诉浏览器它用于授权的用户名/密码。

我试过了:

  • 旧的“用户名:密码@主机”格式(不安全,不再允许在IE上使用)。
  • HTTPWebRequest,它给出了我之前描述的问题。

考虑:

  • 正在访问的远程服务器是一个黑盒子。

有没有办法实现这个目标? (也可以在JavaScript中完成。)

这是我对HttpRequest的函数:

    public void DoWebRequest(String email, String psw, String hostname, 
    int port, String req_method, String webpage)
    {

    String path = hostname + ":" + port + "/" + webpage;
    String userdata = email + ":" + psw;
    System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] data = encoding.GetBytes(path);
    byte[] authBytes = Encoding.UTF8.GetBytes(userdata.ToCharArray());
    String req_short_host_temp = hostname;
    String req_short_host = req_short_host_temp.Replace("http://", "");

    Uri uri = new Uri(path);
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri) as HttpWebRequest;
    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)";
    req.Method = req_method;
    req.PreAuthenticate = false;
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
    req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    req.Headers.Add("Accept-Language: en-us,en;q=0.5");
    req.Headers.Add("Accept-Encoding: gzip,deflate");
    req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    req.KeepAlive = true;
    req.Headers.Add("Keep-Alive: 1000");
    req.ReadWriteTimeout = 320000;
    req.Timeout = 320000;
    req.Host = req_short_host;
    req.AllowAutoRedirect = true;

    req.ContentType = "application/x-www-form-urlencoded";
    req.Headers.GetType().InvokeMember("ChangeInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, req.Headers, new object[] { "Host", req_short_host });

    var headers = new MyHeaderCollection();
    req.Headers = headers;
    headers.Set("Host", req_short_host);

    StreamWriter sw = new StreamWriter(req.GetRequestStream());
    sw.Write("/" + "?user=" + email + "&password=" + psw);
    sw.Close();

    HttpWebResponse response = (HttpWebResponse)req.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string tmp = reader.ReadToEnd();

    foreach (Cookie cook in response.Cookies)
    {
        tmp += "\n" + cook.Name + ": " + cook.Value;
    }

    Response.Write(tmp);
    Response.End();

}

1 个答案:

答案 0 :(得分:0)

不知道javascript,但我认为c#中没有办法做到这一点。您可以过滤所有用户交互,以便浏览器永远不会直接访问其他服务器。为此,请重写内容中的所有URL以指向您的脚本(反向代理)。