php - 从 API (oauth2) 获取访问 token

标签 php python oauth-2.0

我是 Python 脚本的初学者,但遇到了问题。

我正在尝试将 PHP 代码重写为 Python 以从 API 获取访问 token 以供进一步使用。

##/* Request for access token */

$base_url = "myurl";
$client_id="1234";
$client_secret="5678";

$client_details = "${client_id}:${client_secret}";

$context = stream_context_create(array(
    'http' => array(
    'method' => 'POST',
    'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
                "Authorization : Basic $client_details\r\n",
    'content' => "grant_type=client_credentials"
    )
));

$response = file_get_contents($base_url.'/apis/oauth2/Token.php', false, $context);
$res =  json_decode($response);
$token = $res->access_token;

这就是我想用 Python 做的事情。

我的 Python 代码是:

import urllib
import sys
import json
import requests

base_url = 'myurl'
client_id='1234'
client_secret='5678'

response = requests.post(base_url+'/apis/oauth2/Token.php',
                    auth=(client_id, client_secret))

print(response.json())

但这行不通

Python 正在回归:

{'error': 'invalid_request', 'error_description': 'The grant type was not specified in the request'}

我知道我遗漏了 PHP 代码中上下文变量的所有内容。您知道是否有 Python 方法可以在 PHP 中创建类似 stream_context_create 的上下文,或者您能否给我一些提示,我该怎么做?

最佳答案

我设法解决了我的问题。 这是代码:

import urllib
import sys
import json
import requests

base_url = 'https://myurl.com'
client_id='1234'
client_secret='5678'
grant_type='client_credentials'

response = requests.post(base_url+'/apis/oauth2/Token.php',
                        auth=(client_id, client_secret),
                         data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
print(response.json())

关于php - 从 API (oauth2) 获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761307/

相关文章:

python - Django 模型继承和类型检查

Android WebView - 表单数据持久化

python - Microsoft Graph 身份验证

nginx - Istio:最终用户身份验证中的 auth url 支持

javascript - Firebase 创建用户 "manually"

c# - SSL 是从远程到网络服务器交换信息的唯一途径吗?

php - 如何通过字段下订单但内部有条件?

python - 如何使用范围将两个不同列表中的项目配对?

php - 什么定义了有效的对象状态?

python - 使用带有哨兵对象的默认参数的 Sphinx python 方法进行记录?