NodeJS 来自R的Ghost CMS API

tv6aics1  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(88)

我正在尝试使用内置的Admin API从R连接到本地Ghost CMS示例。有一个很好的文档(https://ghost.org/docs/admin-api/#token-authentication)介绍了如何连接各种语言,但不幸的是没有用于R。我已经编译了下面的代码,但不幸的是,在尝试创建测试帖子时收到401错误。任何帮助都是非常感谢的。

R代码:

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))

字符串

omvjsjqw

omvjsjqw1#

看起来问题出在您传递给jwt_encode_hmac()secret=上。charToRaw不理解十六进制数字。它只是使用了ASCII字符代码。要进行转换,您需要this existing question中的一个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”。

相关问题