<p>我正在尝试使用内置的Admin API从R连接到本地的Ghost CMS实例。有一个很好的文档(https://ghost.org/docs/admin-api/#token-authentication),介绍了如何在各种语言中进行连接,但不幸的是没有提供给R的文档。我已经编写了以下代码,但不幸的是在尝试创建一个测试文章时收到了401错误。非常感谢任何帮助。<br /><br />R代码:</p><p><strong></strong></p>
<pre class="brush:php;toolbar:false;">api_admin_key <-
  "xxxxxx:yyyyyyyyyyyyyyy"
api_admin_key <- unlist(strsplit(x = api_admin_key, split = ":"))
names(api_admin_key) <- c("id", "secret")
# Prepare header and payload
iat <- as.integer(Sys.time())
header <-
  list(alg = 'HS256', typ = 'JWT', kid = api_admin_key[["id"]])
# Create the token (including decoding secret)
payload <-
  jose::jwt_claim(iat = iat,
                  exp = iat + 5 * 60,
                  aud = '/admin/')
token <-
  jose::jwt_encode_hmac(
    claim = payload,
    secret = charToRaw(api_admin_key[["secret"]]),
    size = 256,
    header = header
  )
# Make an authenticated request to create a post
url <- 'http://localhost:2368/ghost/api/admin/posts/'
headers <- c('Authorization' = paste("Ghost", token))
body <- list(posts = list(
    "title" = 'Hello World',
    "html" = "<p>My post content. Work in progress...</p>",
    "status" = "published"
  )
)
httr::POST(url,
           body = body,
           encode = "json",
           httr::add_headers(.headers = headers))</pre>
<p><br /></p>            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
         
        
        
看起来问题出在你传递给jwt_encode_hmac()的secret=参数上。charToRaw函数无法理解十六进制数字,它只使用ASCII字符码。要进行转换,你需要使用现有问题中的其中一个hex_to_raw函数。我在这里使用一个函数来进行转换。
hex_to_raw <- function(x) { digits <- strtoi(strsplit(x, "")[[1]], base=16L) as.raw(bitwShiftL(digits[c(TRUE, FALSE)],4) + digits[c(FALSE, TRUE)]) }另外,你不需要在头部指定alg和typ,因为这些会由函数自动添加。所以你可以使用以下方式构建你的令牌:
api_admin_key <- "adam:12bd18f2cd12" api_admin_key <- unlist(strsplit(x = api_admin_key, split = ":")) names(api_admin_key) <- c("id", "secret") # Prepare header and payload iat <- as.integer(Sys.time()) header <- list(kid = api_admin_key[["id"]]) # Create the token (including decoding secret) payload <- jose::jwt_claim(iat = iat, exp = iat + 5 * 60, aud = '/admin/') token <- jose::jwt_encode_hmac( claim = payload, secret = hex_to_raw(api_admin_key[["secret"]]), size = 256, header = header )我使用https://jwt.io/上的调试器测试了每个令牌,它们似乎是等价的。在调试器中,十六进制值"12bd18f2cd12"的Base64编码值是"Er0Y8s0S"。