【问题标题】:Nginx 401 with PHP cURL带有 PHP cURL 的 Nginx 401
【发布时间】:2020-10-09 07:56:19
【问题描述】:

为了获取 oAuth2 令牌,我必须通过发送 base64_encode(api_client_id:api_secret) 连接到此 URL 的 REST API:https://abcd/api/oauth/v1/token。此外请注意,对https://abcd/api/oauth/v1/token 的访问受到htpwd 的保护。

所以我用 PHP 编写的请求是:

$base64_encoded_client_id_and_secret = base64_encode('api_client_id:api_secret');
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, 'https://abcd/api/oauth/v1/token');
curl_setopt($curl_session, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Basic ' . $base64_encoded_client_id_and_secret]);
curl_setopt($curl_session, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl_session, CURLOPT_USERPWD, "htpwd_user:htpwd_pwd");
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, [
    'grant_type' => 'password',
    'username'  =>  'api_user',
    'password'  =>  'api_pwd'
    ]);
$ret = json_decode(curl_exec($curl_session));

但是 Nginx 服务器返回错误 401。我可以做些什么来修复这个错误?

我测试了不同的值而不是 CURLAUTH_DIGEST ;没有工作。

是 CROOS Origin 问题吗?

【问题讨论】:

  • 这个 -curl_setopt($curl_session, CURLOPT_HTTPHEADER, [ .... 'Authorization: Basic ' . $base64_encoded_client_id_and_secret]) 和这个 - curl_setopt($curl_session, CURLOPT_USERPWD, "htpwd_user:htpwd_pwd");都在做同样的事情!所以你只需要使用 1
  • @AngelDeykov 我必须提供 htpwd 访问数据和 API 访问数据 ^^
  • 这种方式肯定做不到。确保您已遵循您正在使用的文档。换句话说,现在您正在尝试添加 2 个 HTTP 授权标头 ...
  • 我找到了 1 个可以帮助您的主题,请查看第一个答案,其中建议用逗号分隔字段值 - stackoverflow.com/questions/29282578/…

标签: php nginx curl oauth-2.0 http-status-code-401


【解决方案1】:

即使有效,以下解决方案也不是一个好的解决方案(阅读以下内容)。通过在任意时间段内删除 htpasswd 安全步骤(等于我的测试和开发时间的总和)解决了该问题。如果您这样做,请小心,因为 Google 可能会从属于此时间间隔的时刻开始索引该网站。

我没有尝试按照@AngelDeykov 在评论中(不是在答案中)提出的用逗号分隔字段值。

【讨论】:

    猜你喜欢
    • 2016-11-08
    • 2011-07-19
    • 1970-01-01
    • 2015-07-31
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多