如何使用curl命令行访问具有HTTP基本认证的网页

5

我曾经在终端中使用curl命令访问一个php网页,以测试网页中的一些API。这个方法非常有效。

例如:

curl www.somesite.com -d parmetername=value 

现在这个页面有基本的http身份验证。我知道只需要添加“-u”来提供用户名和密码。我还查了一下谷歌,几乎每个人都建议按照以下方式进行:

curl -u username:password www.somesite.com -d parmetername=value
curl --user username:password www.somesite.com -d parmetername=value 

或者

curl http://username:password@www.somesite.com -d parmetername=value

我已经尝试了这两个方法,但都无效。我收到了以下相同的错误信息:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
<p>Additionally, a 401 Authorization Required
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>
<address>Apache/2.2.29 (Unix) mod_ssl/2.2.29 OpenSSL/1.0.1e-fips mod_bwlimited/1.4 Server at www.somesite.com Port 80</address>
</body></html>

我尝试通过浏览器访问网站。在弹出窗口中输入用户名和密码后,我可以访问该网站。
有人知道这里发生了什么吗?谢谢。

请再检查一下您在URL中输入的用户名和密码,因为这对我(在个人服务器上)是有效的。 - watery
可能是 https://dev59.com/YHA75IYBdhLWcg3w6Ndj 的重复问题。 - Jan
我已经尝试了多次和不同的电脑...还是没有用...我在想这是否与服务器设置有关... - user3293338
https://dev59.com/YHA75IYBdhLWcg3w6Ndj 中提到的解决方案与我的尝试1相同。但它并没有起作用... - user3293338
1个回答

1
当我遇到这个问题时,发现服务器不接受“Basic”身份验证方案,但curl默认使用“Basic”,除非另有规定。
请查看curl的命令行选项,了解身份验证方案。您可以使用--basic、--digest、--ntlm、--negotiate和--anyauth。有关详细信息,请参阅curl的手册页。
虽然--anyauth或--negotiate听起来像curl可以与服务器协商正确的身份验证方法,但对我来说都不起作用。相反,我必须明确使用--digest,如下所示:
curl --digest -u username:password -d parm1=value1&parm2=value2&submit=true https://www.somesite.com 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接