【问题标题】:curl http auth work perfect in command line but on php notcurl http auth 在命令行中完美运行,但在 php 上却不行
【发布时间】:2016-11-18 05:09:54
【问题描述】:

你好,我有命令行代码:

curl 'http://192.168.0.1:80/' -H 'Authorization: Basic my_auth'

在php中:

$process = curl_init($ip);
//just for "shore"
            curl_setopt($data, CURLOPT_HTTPHEADER,
            array(
              "Authorization: Basic " . base64_encode($username . ":" . $password)
            ));
            curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($process, CURLOPT_USERPWD, $login . ":" . $password);
            curl_setopt($process, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($process, CURLOPT_TIMEOUT, 10);

            curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($process, CURLOPT_VERBOSE, 1);
            curl_setopt($process, CURLOPT_HEADER, 1);

            $return = curl_exec($process);

结果我看到:401... 在 apache2 日志中:

  • HTTP 1.0,假设在正文之后关闭
  • 关闭连接 53
  • 向此 URL 发出另一个请求:''
  • 在 DNS 缓存中找到主机名
  • 正在尝试 192.168.0.1...
  • 连接到 192.168.0.1 (192.168.0.1) 端口 80 (#54)
  • 使用 Basic 和用户 'admin' 的服务器身份验证

    GET / HTTP/1.0 授权:基本 my_code 主机:192.168.0.1 接受:/

  • HTTP 1.0,假设在正文之后关闭

  • 身份验证问题。忽略这一点。
  • 关闭连接 54

【问题讨论】:

  • 天哪,大错特错 ))) "shore" => "sure") 对不起我的英语不好
  • 已解决:curl_setopt($process, CURLOPT_COOKIEFILE, 'cookiefile.txt');

标签: php authentication curl http-authentication


【解决方案1】:

这不是您使用 curl 发送基本身份验证的方式。对于 Basic,预期的标头是 Authorization: Basic <base64 encoded string>,其中编码的字符串是 `:。使用 curl(假设没有其他配置)执行此 OOTB 的方法是使用“-u”开关。示例:

curl -u "user:pass" http://<endpoint>/

如果您“手动”发送标头,则必须先自己对其进行 base64 编码。

现在,您的 PHP 代码是正确的,而您的 curl 调用不正确。这意味着服务解释 Authorization 的方式存在问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多