r语言 - 将curl OAuth2令牌请求转换为http



我正在尝试使用r和http访问domain.com.au api。我可以使用API密钥实现这一点,但不能使用OAuth2

文档显示:

通过Client Credentials获取访问令牌使用您的client_id和client_secret以及所需的范围列表向https://auth.domain.com.au/v1/connect/token端点发出POST请求。请参阅API参考,了解每个端点所需的作用域列表。尝试使用计划中未包含的范围将导致400 invalid_scope错误。此请求必须使用基本身份验证,其中client_id和client_secret分别对应于用户名和密码。

https://developer.domain.com.au/docs/v2/authentication/oauth/client-credentials-grant

curl实现很简单:

curl -X POST -u 'clientid:secret' -H "Content-Type: application/x-www-form-urlencoded" -d 'grant_type=client_credentials&scope=api_listings_read%20api_agencies_read' 'https://auth.domain.com.au/v1/connect/token'

返回不重定向的令牌。

但是,我一直无法将其转换为等效的http POST请求以获得令牌。我现在拥有的是:

oep <- oauth_endpoint(base_url = "https://auth.domain.com.au/v1/connect/token", 
request = NULL, 
access = "access_token" )
myapp <- oauth_app("domain",
key = "client_id_here",
# The secret isn't secrete. A user still has to authenticate when redirected.
secret = "secret_here"
)
# Retrieve the token
token <- oauth2.0_token(oep, 
myapp, 
scope = "api_listings_read")

这不必要地重定向到一个未知的页面,我关闭它,然后返回到控制台,我按escape退出。

我正在复习在R中将cURL转换为http,但到目前为止还没有成功。

任何帮助都将非常感激。

我解决了这个问题。似乎最简单的解决方案是在

的正文中包含所有内容。
r <- POST("https://auth.domain.com.au/v1/connect/token",
config = list(),
body = list(
grant_type="client_credentials",
client_id="myclientid",
client_secret="mysecret",
scope="api_suburbperformance_read"
),
encode = "form"
)
warn_for_status(r)          
content(r)
$access_token
[1] "my_requested_token"
$expires_in
[1] 43200
$token_type
[1] "Bearer"
tok <- content(r)$access_token
rg <- GET("https://api.domain.com.au/v2/suburbPerformanceStatistics/NSW/Pyrmont/2009",
add_headers("Content-Type"="application/x-www-form-urlencoded",
Accept="text/plain",
"Authorization"=paste("Bearer", tok)))
warn_for_status(rg)

content(rg)
$header
$header$suburb
[1] "Pyrmont"
$header$state
[1] "NSW"
$header$propertyCategory
[1] "House"

$series
$series$seriesInfo
$series$seriesInfo[[1]]
$series$seriesInfo[[1]]$year
[1] 2020
$series$seriesInfo[[1]]$month
[1] 2

etc. etc.

其中form是包含Content-Type: application/x-www-form-urlencoded的简写。

我计算出Accept="text/plain"应该包含在get请求中,方法是转到端点文档https://developer.domain.com.au/docs/v2/apis/pkg_properties_locations/references/suburbperformance_get_bynamedsuburb并遵循"Try it out"指令,以便我可以查看curl命令结构(注意下面命令的-H部分)。

curl -X GET "https://api.domain.com.au/v2/suburbPerformanceStatistics/NSW/Pyrmont/2009?bedrooms=3&startingPeriodRelativeToCurrent=1&totalPeriods=4" -H "accept: text/plain" -H "Authorization: Bearer my_requested_token"

作为一个使用httr的初学者,我想说的是,除了常规或常见的用例之外,这个api似乎对任何情况都没有特别的帮助。它在抽象用户的底层细节方面走得太远了。一个小插曲来处理像这样的非标准情况会有所帮助。然而,我承认我的评论可能只是因为不得不花几个小时来弄清楚如何实现一个应该是微不足道的简单过程而产生的沮丧。

我将把这个问题搁置几天,看看是否有人能提出更好的替代方案或提供一些额外的启发。

最新更新