【问题标题】:GET Access token from API (oauth2)从 API (oauth2) 获取访问令牌
【发布时间】:2023-04-05 12:17:01
【问题描述】:

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

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

##/* 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 这样的上下文,或者你能给我一些提示,我该怎么做?

【问题讨论】:

  • docs.python-requests.org/en/latest/user/quickstart/… - json 成员是一个方法,而不是一个值。尝试添加括号:print(response.json())
  • 谢谢我离我的令牌更近了一点:)
  • 您的 python 代码似乎在执行与 php 完全不同的请求,因此它不起作用也就不足为奇了,假设您正在针对与 php 完全相同的服务运行 python。 php 执行 POST,您的 Python 执行 GET。 php 填充了一些标题并提供了内容,python 似乎也没有这样做,您将 auth 放入查询字符串中。您是否尝试过让 python 版本 exactly 与 php 执行相同的 POST?不确定您所说的上下文是什么意思,但请求确实有一个会持续存在的会话,例如跨多个 get/post 的 cookie。
  • 你说得对,我改了发帖。我的意思是上下文?我的意思是 $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n" )。 "授权 : 基本 $client_details\r\n", 'content' => "grant_type=client_credentials" ) ));
  • 这更适合您想要实现的目标,会让它变得轻而易举github.com/requests/requests-oauthlib

标签: php python oauth-2.0


【解决方案1】:

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

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())

【讨论】:

    猜你喜欢
    • 2022-11-28
    • 1970-01-01
    • 2011-07-28
    • 2021-11-10
    • 1970-01-01
    • 2020-08-01
    • 2015-07-27
    • 1970-01-01
    • 2015-02-11
    相关资源
    最近更新 更多