如何通过 R 解决来自 MS Dataverse 的 401 错误?

How can I troubleshoot a 401 error from MS Dataverse through R?

昨天我使用以下代码通过 R 从我的 MS Dataverse 中获取数据。它工作正常。

require(httr)
require(rvest)

dataverse_api = oauth_endpoint(request = NULL, 
   authorize = "https://login.microsoftonline.com/REDACTED/oauth2/v2.0/authorize",
   access = "https://login.microsoftonline.com/REDACTED/oauth2/v2.0/token",
   base_url = "https://login.microsoftonline.com/common/oauth2/authorize?resourcehttps://org593dc393.crm4.dynamics.com")

API.Key = "REDACTED"
API.Secret = "REDACTED"

App = oauth_app("EPS Project Development", key = API.Key, secret = API.Secret)

API.token = oauth2.0_token(dataverse_api, App, scope = "https://org593dc393.crm4.dynamics.com/.default")
API.AuthKey = API.token$credentials$access_token

GET.Buildings = GET("https://org593dc393.crm4.dynamics.com/api/data/v9.2/crfd0_dartbuildingses", add_headers(Authorization = paste("Bearer", API.AuthKey, sep = " ")))

今天,尝试 运行 没有修改的相同代码行给我一个 401 错误。基于对调试 401 错误(none 特定于 MS Dataverse)的一些研究,我尝试清除我的缓存,清除我的 cookie,使用 ipconfig/flushdns 刷新我的 DNS 并直接导航到端点并检查请求,它返回了以下 200 响应:

经过所有这些努力,尽管该代码昨天有效,但我仍然在 R 中收到以下响应:

我还使用 Postman 生成了一个新令牌。当我 运行 使用该令牌的 GET 命令时,我得到状态 200。

API.AuthKey = "REDACTED TOKEN FROM POSTMAN"
GET.Buildings = GET("https://org593dc393.crm4.dynamics.com/api/data/v9.2/crfd0_dartbuildingses", add_headers(Authorization = paste("Bearer", API.AuthKey, sep = " ")))

GET.Buildings$status_code
[1] 200

R 对我最初尝试的回应中的任何人都清楚我做错了什么吗?如果没有,我该如何调试?

原来代码每次都提供相同的访问令牌。我只需要添加 cache = FALSE 这样我就不会使用缓存的令牌。如果对任何人有帮助,完整代码现在是:

require(httr)
require(rvest)

dataverse_api = oauth_endpoint(request = NULL, 
   authorize = https://login.microsoftonline.com/REDACTED/oauth2/v2.0/authorize,
   access = https://login.microsoftonline.com/REDACTED/oauth2/v2.0/token,
   base_url = https://login.microsoftonline.com/common/oauth2/authorize?resourcehttps://org593dc393.crm4.dynamics.com)

API.Key = "REDACTED"
API.Secret = "REDACTED"

App = oauth_app("EPS Project Development", key = API.Key, secret = API.Secret)

API.token = oauth2.0_token(dataverse_api, App, scope = https://org593dc393.crm4.dynamics.com/user_impersonation, cache = FALSE)
API.AuthKey = API.token$credentials$access_token

GET.Buildings = GET(https://org593dc393.crm4.dynamics.com/api/data/v9.2/crfd0_dartbuildingses, add_headers(Authorization = paste("Bearer", API.AuthKey, sep = " ")))