【问题标题】:How to get an OAuth 2.0 token in PHP?如何在 PHP 中获取 OAuth 2.0 令牌?
【发布时间】:2021-04-30 20:06:20
【问题描述】:

我需要连接到客户的 REST API。第一步是获取 OAuth 2.0 访问令牌。我从客户那里得到了以下信息:

  • 登录(我猜是client_id
  • 密码(我猜是client_secret
  • 流量为password
  • 常规 API URL
  • 令牌 API 网址

我在以下位置找到了代码 http://tutorialspage.com/simple-oauth2-example-using-php-curl/ 并将其更改为仅用于测试:

private function getToken() {

    $curl = curl_init();

    $params = array(
        CURLOPT_URL =>  self::API_TOKEN_URL,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_POST => 1,
        CURLOPT_NOBODY => false,
        CURLOPT_HTTPHEADER => array(
            "cache-control: no-cache",
            "content-type: application/x-www-form-urlencoded",
            "accept: *",
            "accept-encoding: gzip, deflate",
        ),
        CURLOPT_POSTFIELDS => array(
            'username' => urlencode('example@swagger.foo'),
            'password' => urlencode('123 and 4'),
            'grant_type' => 'password'
        )
    );

    curl_setopt_array($curl, $params);
    // test
      //curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
      //curl_setopt($curl, CURLOPT_USERPWD, 'example@swagger.foo'.':'.'123 and 4');

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        echo "cURL Error #01: " . $err;
    } else {
        $response = json_decode($response, true);
        if(array_key_exists("access_token", $response)) return $response;
        if(array_key_exists("error", $response)) echo $response["error_description"];
        echo "cURL Error #02: Something went wrong! Please contact admin.";
    }
}

我希望得到一个包含有效 OAuth 2.0 access_token 的 JSON 响应,但我得到了一个错误:

{"error":"unsupported_grant_type"}

如何更改代码以使其正常工作?

编辑: 它适用于我的 mac 上的 shell-curl:

  curl -i \
  -X POST \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=password&username=example@swagger.foo&password=123 and 4' \
  https://the-token-api-url.foo

详细信息卷曲(MacShell):

*   Trying <IP HOST>
* TCP_NODELAY set
* Connected to <DNS HOST> (<IP HOST>) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /opt/local/share/curl/curl-ca-bundle.crt
  CApath: none
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / <something>
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: CN=<CN>
*  start date: <date>
*  expire date: <date>
*  subjectAltName: host "<DNS HOST>" matched cert's "<DNS HOST>"
*  issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3
*  SSL certificate verify ok.
> POST /<URI PART>/token HTTP/1.1
> Host: <DNS HOST>
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Type: application/x-www-form-urlencoded
> Content-Length: 73
> 
* upload completely sent off: 73 out of 73 bytes
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Cache-Control: no-cache
Cache-Control: no-cache
< Pragma: no-cache
Pragma: no-cache
< Content-Type: application/json;charset=UTF-8
Content-Type: application/json;charset=UTF-8
< Expires: -1
Expires: -1
< Server: Microsoft-IIS/8.5
Server: Microsoft-IIS/8.5
< X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
< Date: Tue, 05 Feb 2019 17:26:21 GMT
Date: Tue, 05 Feb 2019 17:26:21 GMT
< Content-Length: 671
Content-Length: 671

详细信息 cURL PHP:

* Hostname in DNS cache was stale, zapped
*   Trying <IP>
* TCP_NODELAY set
* Connected to <DNS> (<IP>) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /opt/local/share/curl/curl-ca-bundle.crt
  CApath: none
* SSL connection using TLSv1.2 / <something>
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: CN=<DNS>
*  start date: <date>
*  expire date: <date>
*  subjectAltName: host "<dns>" matched cert's "<dns>"
*  issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3
*  SSL certificate verify ok.
> POST /<uri part>/token HTTP/1.1
Host: <dns>
cache-control: no-cache
accept: *
accept-encoding: gzip, deflate
Content-Length: 384
Content-Type: application/x-www-form-urlencoded; boundary=------------------------<a hash>

< HTTP/1.1 400 Bad Request
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: application/json;charset=UTF-8
< Expires: -1
< Server: Microsoft-IIS/8.5
< X-Powered-By: ASP.NET
< Date: Tue, 05 Feb 2019 17:25:39 GMT
< Content-Length: 34
* HTTP error before end of send, stop sending
< 
* Closing connection 0

我没发现问题。

【问题讨论】:

  • grant_type 更改为 password 并删除 redirect_uri。您可能还需要使用username/password 而不是client_id/client_secret,或者您可能需要将这些值用作基本身份验证用户名/密码(通过Authorization: Basic ... 标头传递)。作为参考,下面是使用密码流(又名资源所有者密码凭证)的 OAuth 2.0 令牌请求的样子:tools.ietf.org/html/rfc6749#section-4.3.2
  • 谢谢海伦。我对您提到的更改进行了很多尝试。但没有成功。我还发现授权类型始终不受支持,我尝试了在您链接的 oAuth2 RFC 和 Swagger Doc 中可以找到的所有授权类型。我将问题中的代码更新为我的实际(并且在我看来是最正确的)版本。
  • This comment 建议您应该使用 CURLOPT_POSTFIELDS =&gt; http_build_query($post_fields_array) 而不是直接传递数组。这行得通吗?另外,您可能不需要urlencode usernamepassword,curl 应该会为您处理。
  • 谢谢,已经解决了。我用我的最终代码创建了一个答案。

标签: php oauth-2.0


【解决方案1】:

好的,多亏了 Helen,它现在可以工作了。

private function getToken(){
    $curl = curl_init();

    $params = [
        CURLOPT_URL =>  self::API_TOKEN_URL,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,

        CURLOPT_POST => 1,
        CURLOPT_NOBODY => false,
        CURLOPT_HTTPHEADER => array(
            "cache-control: no-cache",
            "content-type: application/x-www-form-urlencoded",
            "accept: */*",
            "accept-encoding: gzip, deflate",
        ),
        CURLOPT_POSTFIELDS => "grant_type=password&username=username@example.foo&password=123and4"
    ];

    curl_setopt_array($curl, $params);
    $response = curl_exec($curl);

    curl_close($curl);
}

当我将 Post Data 作为字符串输入时,问题就解决了: CURLOPT_POSTFIELDS =&gt; "grant_type=password&amp;username=username@example.foo&amp;password=123and4" 而不是数组:

CURLOPT_POSTFIELDS => array(
            'username' => urlencode('username@example.foo'),
            'password' => urlencode('123and4'),
            'grant_type' => 'password'
        )

谢谢

【讨论】:

  • 通常你可以使用 http_build_query : CURLOPT_POSTFIELDS => http_build_query(array( 'username' => 'username@example.foo', 'password' => '123and4', 'grant_type' => '密码'))
猜你喜欢
  • 2019-10-17
  • 2012-04-18
  • 2019-09-10
  • 2021-03-20
  • 2023-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-03-03
相关资源
最近更新 更多