faw*_*123 6 r oauth-2.0 httr github-actions
我正在尝试使用 GitHub Actions 通过 R 脚本使用 OAuth 2.0 令牌查询 GitHub API。当我运行代码时,它在我的本地计算机上运行良好,其中弹出一个浏览器窗口,指示“等待浏览器中的身份验证...”,我可以手动关闭该窗口。通过 GitHub Actions 运行时,工作流程会挂在“等待浏览器中的身份验证...”处,因为它位于远程计算机上。
我正在使用带有 httr 库的自定义 R 脚本。API 凭据作为我尝试查询的存储库的机密存储。
library(httr)
gh_key <- Sys.getenv('GH_KEY')
gh_secret <- Sys.getenv('GH_SECRET')
# setup app credentials
myapp <- oauth_app(appname = "data-in-r",
key = gh_key,
secret = gh_secret)
# get oauth credentials
github_token <- oauth2.0_token(oauth_endpoints('github'), app = myapp, cache = F)
# use api
gtoken <- config(token = github_token)
# get list of remote files in data folder
req <- GET("https://api.github.com/repos/tbep-tech/piney-point/contents/data", gtoken)
Run Code Online (Sandbox Code Playgroud)
当脚本通过 GitHub Actions 运行时,如下所示,我必须手动取消工作流程,因为它在浏览器步骤中挂起。
是否有解决方法可以跳过浏览器步骤,使其在 GitHub Actions 上运行?有问题的仓库在这里。
您无法在像 Github Actions 这样的无头环境中使用 OAuth2.0 的 3 足变体(又名“Web 应用程序流”)。
如果您想使用 OAuth(我在下面列出了其他可能性),那么您需要利用 gitlab 所谓的“设备流”。请参阅github 文档。
在此流程中,没有重定向到给定的 URL,因此应用程序不需要浏览器窗口。相反,它会向用户显示代码。用户必须在固定 URL ( https://github.com/login/device )上输入该代码。完成此操作后,应用程序就可以请求身份验证令牌。(因此应用程序必须不断轮询,直到用户输入代码)。
不幸的是,httr这个变体没有很好的包装函数,所以你必须自己进行调用。它可以像这样工作:
library(httr)
app_id <- "*redacted*"
r <- POST("https://github.com/login/device/code",
body = list(
client_id = app_id,
scope = "user repo delete_repo" #Scope must be given! https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps
))
device_code <- content(r)$device_code
print(paste0("Enter the code ", content(r)$user_code, " at ", content(r)$verification_uri))
## NOTE: In reality this request has to run in a loop, until the user has entered the code und the request succeeds.
## For the demo we can execute it manually after the code has been entered.
r <- POST("https://github.com/login/oauth/access_token",
body = list(
client_id = app_id,
device_code = device_code,
grant_type = "urn:ietf:params:oauth:grant-type:device_code"
))
token <- content(r)$access_token
## create and delete a private testrepository to check if everything worked
r <-
POST("https://api.github.com/user/repos",
add_headers(Authorization = paste("token", token)),
body = list(name = "testrepo",
private = TRUE,
auto_init = FALSE),
encode = "json")
r <- DELETE(paste0("https://api.github.com/repos/", content(r)$full_name),
add_headers(Authorization = paste("token", token)))
Run Code Online (Sandbox Code Playgroud)
我已经看到有httr2,并且它为这个流程提供了便利的功能。然而我从未使用过它,也不知道它是否已经可靠地工作。看这里。
由于此流程仍然需要用户交互,因此您可能最好使用以下变体之一(我不知道它们是否适合您的用例。):
基本身份验证:
您可以预先定义 github 所谓的“个人访问令牌”。使用此令牌,您可以进行身份验证,而无需进一步交互。这里描述了创造。在 R 中,您可以最轻松地将它与httr::authenticate.
GITHUB_TOKEN: Github 自动创建特殊秘密,特别是 Github Actions。这些可用于在包含存储库中执行操作。欲了解更多信息,请参见此处。
| 归档时间: |
|
| 查看次数: |
1116 次 |
| 最近记录: |