我有一个使用nginx的Web服务器,配置了HTTPS和基本身份验证。
我尝试使用带有PowerShell的WebClient查询它
$wc = new-object System.Net.WebClient
$wc.Credentials = Get-Credential
return $wc.DownloadString($url)
这适用于以下$url
s
https://server.com
https://server.com/
https://server.com/directory/
https://server.com/page.php
https://server.com/directory/index.php
但对于以下$url
,我得到The remote server returned an error: (401) Unauthorized.
https://server.com/directory
https://server.com/otherdirectory
https://server.com/directory/directory
我起初认为这是由于重定向,但鉴于一些工作示例,这不会有意义。也许这是我的nginx配置?
答案 0 :(得分:0)
我目前认为这是WebClient
课程中的一个错误。以下是我与服务器交互的摘要:
------------------------------------------------------------------------
GET /directory HTTP/1.1
Host: example.com
------------------------------------------------------------------------
HTTP/1.1 401 Unauthorized
Server: nginx/1.4.6 (Ubuntu)
Date: Fri, 27 Jun 2014 02:37:45 GMT
Content-Type: text/html
Content-Length: 203
Connection: keep-alive
WWW-Authenticate: Basic realm="sup"
<html>
<head><title>401 Authorization Required</title></head>
<body bgcolor="white">
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>
------------------------------------------------------------------------
GET /directory HTTP/1.1
Authorization: Basic bmFjaHQ6aGVsbG8=
Host: example.com
------------------------------------------------------------------------
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Fri, 27 Jun 2014 02:37:46 GMT
Content-Type: text/html
Content-Length: 193
Location: http://example.com/directory/
Connection: keep-alive
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>
------------------------------------------------------------------------
GET /directory/ HTTP/1.1
Host: example.com
------------------------------------------------------------------------
HTTP/1.1 401 Unauthorized
Server: nginx/1.4.6 (Ubuntu)
Date: Fri, 27 Jun 2014 02:37:47 GMT
Content-Type: text/html
Content-Length: 203
Connection: keep-alive
WWW-Authenticate: Basic realm="sup"
<html>
<head><title>401 Authorization Required</title></head>
<body bgcolor="white">
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>
------------------------------------------------------------------------
此时,WebClient会抛出异常,说明服务器返回问题中陈述的错误。
它应该为auth令牌提供第三个请求,或者至少使用提供的auth令牌响应另一个请求。
我希望其他人(最好使用.NET 4.5.2)确认这一点,所以我可以接受这个作为答案。