Heim  >  Fragen und Antworten  >  Hauptteil

R-Schnittstelle zur Ghost CMS API

<p>Ich versuche, über die integrierte Admin-API von R aus eine Verbindung zu einer lokalen Ghost CMS-Instanz herzustellen. Es gibt eine gute Dokumentation (https://ghost.org/docs/admin-api/#token-authentication) zum Herstellen einer Verbindung in verschiedenen Sprachen, aber leider gibt es keine Dokumentation für R. Ich habe den folgenden Code geschrieben, erhalte aber leider beim Versuch, einen Testartikel zu erstellen, die Fehlermeldung 401. Jede Hilfe wird sehr geschätzt. <br /><br />R-Code:</p><p><strong></strong></p> <pre class="brush:php;toolbar:false;">api_admin_key <- „xxxxxx:yyyyyyyyyyyyyy“ api_admin_key <- unlist(strsplit(x = api_admin_key, split = ":")) Namen(api_admin_key) <- c("id", "secret") # Header und Payload vorbereiten iat <- as.integer(Sys.time()) Kopfzeile <- list(alg = 'HS256', typ = 'JWT', kid = api_admin_key[["id"]]) # Erstellen Sie den Token (einschließlich Decodierungsgeheimnis) Nutzlast <- jose::jwt_claim(iat = iat, exp = iat + 5 * 60, aud = '/admin/') Token <- jose::jwt_encode_hmac( Anspruch = Nutzlast, Secret = charToRaw(api_admin_key[["secret"]]), Größe = 256, Kopfzeile = Kopfzeile ) # Stellen Sie eine authentifizierte Anfrage, um einen Beitrag zu erstellen URL <- 'http://localhost:2368/ghost/api/admin/posts/' Header <- c('Authorization' = paste("Ghost", token)) body <- list(posts = list( "title" = 'Hallo Welt', "html" = "<p>Mein Beitragsinhalt. In Arbeit...</p>", „status“ = „veröffentlicht“ ) ) httr::POST(url, Körper = Körper, encode = „json“, httr::add_headers(.headers = headers))</pre> <p><br /></p>
P粉134288794P粉134288794444 Tage vor530

Antworte allen(1)Ich werde antworten

  • 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"。

    Antwort
    0
  • StornierenAntwort