【问题标题】:PHP - How to get OAuth 2.0 TokenPHP - 如何获取 OAuth 2.0 令牌
【发布时间】:2019-10-17 16:30:36
【问题描述】:

我想连接到 OAuth 2.0 授权类型(使用密码 grant_type)以使用 POST 方法获取令牌,可以从 Postman 进行测试,但我无法通过 PHP 连接...
这是我的信息:
请求网址:'http://example.com/core/connect/token'
客户名称:'something1'
ClientId:'something2'
秘密:'something3'
用户名:'something4'
密码:'something5'
范围:'something6'

你能给我举个例子来获取令牌和使用吗?

我已经测试过了:

$base_url = 'https://example.com/oauth/token';  

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'client_id'     => YOUR-CLIENT-ID,
        'client_secret' => YOUR-CLIENT-SECRET,
        'username'      => YOUR-USERNAME-OR-EMAIL,
        'password'      => YOUR-PASSWORD,
        'grant_type'    => 'password'
));

$data = curl_exec($ch);

$auth_string = json_decode($data, true);

还有这个

$api = "KEY GOES HERE";
$authurl = "http://example.com/core/connect/token";

$client_id = "ID GOES HERE";
$client_secret = "SECRET GOES HERE";

// Creating base 64 encoded authkey
$Auth_Key = $client_id.":".$client_secret;
$encoded_Auth_Key=base64_encode($Auth_Key);

$headers = array();
$headers['Authorization'] = "Basic ".$encoded_Auth_Key;
$headers['Content-Type'] = "application/x-www-form-urlencoded";

$data = array(
    'grant_type' => 'password',
    'scope'      => 'read write',
    'username'   => $api,
    'password'   => $api,
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $authurl);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

$auth = curl_exec( $ch );

if ( curl_errno( $ch ) ){
    echo 'Error: ' . curl_error( $ch );
}
curl_close($ch);

$secret = json_decode($auth);
$access_key = $secret->access_token;
echo $secret;

【问题讨论】:

    标签: php curl oauth-2.0


    【解决方案1】:

    对于密码授权类型,第一次调用似乎没问题。范围参数应该是可选的。所以...

    将此添加到您的代码中以了解来自服务器的响应,从而了解缺少的参数或设置。

    curl_setopt($ch, CURLOPT_VERBOSE, true);
    

    检查状态代码和可能带有错误消息的正文。

    【讨论】:

    • 什么都不返回
    • 如果你可以在你的项目中使用第三方库,让我向你推荐 PHPLeague 的 OAuth2 客户端库。您可以通过 composer 安装它,它就像一个魅力。oauth2-client.thephpleague.com
    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2015-05-05
    • 2011-02-28
    • 2021-03-20
    相关资源
    最近更新 更多