无法通过XMLHttpRequest通过HTTP身份验证向HTTPS服务器发出POST / GET请求

时间:2016-08-10 10:24:25

标签: ssl xmlhttprequest cors apache2 http-authentication

假设我有两台服务器:服务器A和服务器B.服务器A托管以下页面:

<html>
  <head>
    <script type="text/javascript">
      var http = new XMLHttpRequest();
      console.log("XML Request object created.");

      http.open("POST", 'https://serverb.com/file', true, 'user', 'pass');

      http.onreadystatechange = function() {
        console.log("readystatechange: "+http.status+":"+http.readyState);
        if (http.status == 200 && http.readyState == 4) {
          alert(http.responseText);
        }
      }

      http.send();
      console.log("http request sent.");
    </script>
  </head>
</html>

使用以下Apache2配置:

LoadModule ssl_module modules/mod_ssl.so
LoadModule headers_module modules/mod_headers.so

Listen 443
<VirtualHost *:443>

        Header always append Access-Control-Allow-Origin: "*"
        Header set Access-Control-Allow-Credentials true

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        SSLEngine on
        SSLCertificateFile "/home/vtcakavsmoace/Documents/webpass/cert.pem"
        SSLCertificateKeyFile "/home/vtcakavsmoace/Documents/webpass/key.pem"

</VirtualHost>

服务器B托管一个名为“file”的文件,并具有以下Apache2配置:

LoadModule ssl_module modules/mod_ssl.so
LoadModule headers_module modules/mod_headers.so

Listen 443
<VirtualHost *:443>

    Header always append Access-Control-Allow-Origin: "*"
    Header set Access-Control-Allow-Credentials true

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/files
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <Directory "/var/www/files">
        AuthType Basic
        AuthName "Restricted Content"
        AuthUserFile /etc/apache2/.htpasswd
        Require valid-user
    </Directory>
</VirtualHost>

服务器需要使用密码为“pass”的名为“user”的用户进行HTTP身份验证。

但是,只要有人连接到服务器A,就会出现以下错误:

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

表示Access-Control-Allow-Origin不在标题中。对于任一服务器,情况都不是这样。如果不是问题,我也尝试通过命令行来卷曲信息,这成功了。我还尝试将http.open行更改为:

http.open("POST", 'https://user:pass@serverb.com/file', true);

但这也失败了。

我在这里做错了什么?

修改

如果有帮助,这里是curl --verbose --head -u 'user:pass' https://serverb.com/file的输出:

*   Trying <redacted>...
* Connected to <redacted> (<redacted>) port 443 (#0)
* found 173 certificates in /etc/ssl/certs/ca-certificates.crt
* found 697 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ECDHE_RSA_AES_128_GCM_SHA256
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: <redacted> (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=<redacted>,OU=See www.rapidssl.com/resources/cps (c)15,OU=Domain Control Validated - RapidSSL(R),CN=<redacted>
*    start date: Wed, 06 May 2015 13:02:37 GMT
*    expire date: Mon, 08 May 2017 08:52:24 GMT
*    issuer: C=US,O=GeoTrust Inc.,CN=RapidSSL SHA256 CA - G3
*    compression: NULL
* ALPN, server did not agree to a protocol
* Server auth using Basic with user '<redacted>'
> HEAD /<redacted>/file HTTP/1.1
> Host: <redacted>
> Authorization: Basic <redacted>
> User-Agent: curl/7.47.0
> Accept: */*
> 
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Date: Wed, 10 Aug 2016 11:30:36 GMT
Date: Wed, 10 Aug 2016 11:30:36 GMT
< Server: Apache/2.4.7 (Ubuntu)
Server: Apache/2.4.7 (Ubuntu)
< Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: *
< Last-Modified: Tue, 09 Aug 2016 11:36:29 GMT
Last-Modified: Tue, 09 Aug 2016 11:36:29 GMT
< ETag: "<redacted>"
ETag: "<redacted>"
< Accept-Ranges: bytes
Accept-Ranges: bytes
< Content-Length: 45377
Content-Length: 45377
< Access-Control-Allow-Credentials: true
Access-Control-Allow-Credentials: true
< Content-Type: application/<redacted>
Content-Type: application/<redacted>

< 
* Connection #0 to host <redacted> left intact

编辑2:

我进一步改变了代码。网页中的脚本现在如下:

var http = new XMLHttpRequest();
console.log("XML Request object created.");

http.open("POST", 'https://serverb.com/file', true);

http.withCredentials = true;

http.setRequestHeader('Authorization', 'Basic '+btoa('user:pass'));

http.onreadystatechange = function() {
  console.log("readystatechange: "+http.status+":"+http.readyState);
  if (http.status == 200 && http.readyState == 4) {
    alert(http.responseText);       }
  }

http.send();
console.log("http request sent.");

现在,我得到401状态服务器端和0状态客户端,而不是简单地拒绝该请求,这意味着凭据不正确,即使它们是正确的。

编辑3:

以下编辑会在Chrome中打开身份验证窗格,但在Firefox中,会引发NS_ERROR_DOM_BAD_URI: Access to restricted URI denied错误。

var http = new XMLHttpRequest();
console.log("XML Request object created.");

http.open("GET", 'https://serverb.com/file', true, 'user', 'pass');

http.withCredentials = true;

http.onreadystatechange = function() {
  console.log("readystatechange: "+http.status+":"+http.readyState);
  if (http.status == 200 && http.readyState == 4) {
    alert(http.responseText);
  }
}

http.send();
console.log("http request sent.");

1 个答案:

答案 0 :(得分:0)

好的,所以,我想出了一些解决方法。

由于CORS导致我.navbar-nav{ text-align:center; } .navbar-nav>li { float: none; display: inline-block; } 问题,我摆脱了CORS并开始在Apache2配置中代理请求。

index.html最终版本:

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

服务器A最终配置:

<html>
  <head>
    <script type="text/javascript">
      var http = new XMLHttpRequest();
      console.log("XML Request object created.");

      http.open("POST", 'file', true);

      http.onreadystatechange = function() {
        console.log("readystatechange: "+http.status+":"+http.readyState);
        if (http.status == 200 && http.readyState == 4) {
          alert(http.responseText);
        }
      }

      http.send();
      console.log("http request sent.");
    </script>
  </head>
</html>

服务器B最终配置:

LoadModule ssl_module modules/mod_ssl.so
LoadModule headers_module modules/mod_headers.so
LoadModule rewrite_module modules/mod_rewrite.c
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule auth_basic_module modules/mod_auth_basic.c

Listen 443
<VirtualHost *:443>

        Header always append Access-Control-Allow-Origin: "*"
        Header set Access-Control-Allow-Credentials true

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        SSLEngine on
        SSLCertificateFile "/path/to/cert.pem"
        SSLCertificateKeyFile "/path/to/key.pem"

        ProxyRequests Off
        <Proxy *>
                Order deny,allow
                Allow from all
        </Proxy>

        SSLProxyEngine On
        SSLProxyCheckPeerCN on
        SSLProxyCheckPeerExpire on

        # Adding a prefix for googling purposes.
        ProxyPassMatch "^/(prefix.*file.*.jpg)$" "https://serverb.com/$1"
        ProxyPassReverse "/" "https://serverb.com/"

        <LocationMatch "^/prefix.*file.*.jpg$">

            # Pass the credentials
            AuthBasicFake "user" "pass"
            Order allow,deny
            Allow from all

        </LocationMatch>
</VirtualHost>

此方法的另一个好处是最终用户永远不会看到密码,因此没有授权披露。