且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 R 的 httr 包中使用 oauth2.0 令牌

更新时间:2023-02-16 15:42:59

解决方案

在这个特定用例中——使用 Canvas API——附加信息在请求的header 中是必需的.

Solution

In this particular use case—working with the Canvas API—additional information is required in the header of the request.

使用 httr R 包中的 GET 函数,使用 add_header 参数提供包含您的 oauth2 密钥的参数.

Using the GET function from the httr R package, use the add_header parameter to supply the argument including your oauth2 key.

如果您不想将密钥硬编码到请求中,请使用选项 1(推荐).或者,使用选项 2 并将密钥作为字符串插入.但在这两种情况下,Bearer"在键之前.

Use Option 1 if you don't want to hard code your key into the request (recommended). Or, use Option 2 and insert the key as a string. But in both cases, "Bearer " precedes the key.

# Set Up
url = "https://canvas.{institution}.edu/api/v1/courses"
key = "{secret_key}"

# OPTION 1
GET(url, add_headers(Authorization = paste("Bearer", key, sep = " ")))

# OPTION 2
courses.request = GET(url, add_headers(Authorization = "Bearer {secret_key}"))

#进一步说明

  • Explanation of Authorization Header
  • Rationale for why "Bearer " must go before the key.
  • The OAuth Bible is useful for understanding components of a request

其他人能否解释为什么 OP 的示例没有起作用的其他原因?

Can anyone else explain other reasons why the OP's examples didn't work?