首頁  >  問答  >  主體

Ghost CMS API 的 R 接口

<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>
P粉134288794P粉134288794444 天前532

全部回覆(1)我來回復

  • P粉739706089

    P粉7397060892023-08-04 09:11:43

    看起來問題出在你傳給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"。

    回覆
    0
  • 取消回覆