【问题标题】:Password Grant generate token using HTTR package in R OAuth2密码授予使用 R OAuth2 中的 HTTR 包生成令牌
【发布时间】:2021-06-23 03:02:11
【问题描述】:

对 API 来说是全新的,而且有点过头了。阅读了一下并四处寻找,但仍然感到困惑。我得到了在 curl 中运行的以下代码,以使用 oauth2 和密码授权生成令牌。我想在 R 中实现这段代码并遇到一些问题。

curl -H "Content-type: application/x-www-form-urlencoded" -H "Authorization: Basic xxxyyy123xxx==" -d "grant_type=password&username={username}&password={password}" https://{website}.com/rest/v2/oauth/token

当我在终端中运行上述命令时,它会生成一个令牌,我已使用此代码在 R 中成功使用该令牌:

token <- {character string generated by the above curl command}    
call <- "https://{website}.com/rest/v2/services/APIService/getRegistryRecordByAccessionID?id={id#}"
df <- as.data.frame(fromJSON(content(httr::GET(call, add_headers(Authorization = paste("Bearer", token))), "text"), flatten = TRUE))

我想要的只是在 R 中生成令牌,而不是像以前那样使用另一个程序。这就是我的错误出现的地方。我认为的基本格式是:

token <- oauth2.0_token(endpoint = oauth_endpoint(
                                    authorize = NULL,
                                    access = "https://{website}.com/rest/v2/oauth/token"),
                        app = oauth_app(), #not sure how to set this up
                        use_basic_auth = T,
                        add_headers(Content-type = "application/x-www-form-urlencoded",
                                    Authorization = "Basic xxxyyy123xxx==") #not sure if i need the authorization header here, I believe I need the content-type heder
)

【问题讨论】:

  • 如果你只是想复制那个 CURL 命令,那么你不需要oauth2.0_token。您可以使用httr::POST 更轻松地执行基本请求。还有 curlconverter 包可以更直接地将 CURL 转换为 R。
  • 我将如何使用上面的 CURL 命令通过 POST 来解决这个问题?
  • 你可以试试httr::POST("https://{website}.com/rest/v2/oauth/token", body=list(grant_type="password", "username="{username}", password="{password}"), encode="form")查看帮助页面:httr.r-lib.org/reference/POST.html
  • @MrFlick 我刚刚使用您以前喜欢的 curlconverter 包创建了它。谢谢你。但这会返回一个响应对象,其中不包含我要集成到我的 GET 动词中的令牌。谢谢。
  • 当我们无法实际运行和测试代码时,很难提供具体的建议。如果您是 httr 的新手,请务必阅读帮助页面和可用示例。您使用content() 从响应对象中获取数据。

标签: r api oauth-2.0 httr


【解决方案1】:

从上面 MrFlick 的 cmets 中,我们可以使用 httr 包将 curl 授权命令集成到 POST 中。然后我们查看返回的对象的内容,该对象将在列表的第一项中包含访问令牌。

token <- content(httr::POST("https://{website}.com/rest/v2/oauth/token", body=list(grant_type="password", "username="{username}", password="{password}"), encode="form"))[[1]]

【讨论】:

    猜你喜欢
    • 2019-08-06
    • 2015-07-21
    • 2017-10-08
    • 2017-04-07
    • 2018-02-01
    • 2017-04-09
    • 2017-10-05
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多