【问题标题】:Connecting to OpenID using PHP cURL Showing Error使用 PHP cURL 连接到 OpenID 显示错误
【发布时间】:2018-04-09 23:15:03
【问题描述】:

我正在使用以下代码从使用 OpenID 协议的 IdentityServer 请求令牌:

$curl = curl_init( 'https://remoteserver.com/connect/token' ); 
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$code = $_GET['code'];  // The code from the previous request
$redirect_uri = 'http://mycalldomain.com/test.php';

curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
    'redirect_uri' => $redirect_uri,
    'grant_type' => 'authorization_code'
) );

curl_setopt( $curl, CURLOPT_USERPWD,
    "MYCLIENTID" . ":" . 
    "MYCLIENTSECRET");

$auth = curl_exec( $curl ); 
print '$auth = ';print_r($auth); // to see the error
$secret = json_decode($auth); 
$access_key = $secret->access_token;

正在输出以下错误:

$auth = {"ErrorMessage":"Unsupported Mediatype"}

有人可以指导一下吗?

【问题讨论】:

    标签: php curl oauth openid identityserver3


    【解决方案1】:

    您应该提供一个 Content-Type HTTP 标头,供您发布的资源接受,方法是添加如下内容:

    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    

    这将使它成为 JSON(例如!),并且您的输出数据 (CURLOPT_POSTFIELDS) 必须与您选择的 Content-Type 相对应。

    目前,根据PHP documentation,Content-Type 是“multipart/form-data”:

    如果 value 是一个数组,则 Content-Type 标头将设置为 multipart/form-data。

    如果您想使用 Content-Type “application/x-www-form-urlencoded”,那么除了将其设置为 Content-Type 之外,您还必须以该格式提供 CURLOPT_POSTFIELDS。作为一种 Web 开发语言,PHP 有一个内置函数 http_build_query 用于以该格式编码数组:

    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
        'redirect_uri' => $redirect_uri,
        'grant_type' => 'authorization_code'
    )));
    

    【讨论】:

    • 我已经设置了,但仍然返回相同的错误。从进一步调查来看,该值似乎不应该在 json - openid.net/specs/openid-connect-core-1_0.html#TokenRequest
    • 你能帮我重新格式化我的代码,因为我不确定如何使用以下类型发送:application/x-www-form-urlencoded
    • 我也编辑了答案以提供一个示例。一般来说,在进行 POST 时,不仅要确定预期的 Content-Type,还要确定 POST 数据的格式。许多库都有默认值,因此格式可能从代码中看不出来如果没有明确设置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2015-06-20
    相关资源
    最近更新 更多