看起來問題出在你傳遞給jwt_encode_hmac()的secret=參數(shù)上。charToRaw函數(shù)無法理解十六進制數(shù)字,它只使用ASCII字符碼。要進行轉(zhuǎn)換,你需要使用現(xiàn)有問題中的其中一個hex_to_raw函數(shù)。我在這里使用一個函數(shù)來進行轉(zhuǎn)換。
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,因為這些會由函數(shù)自動添加。所以你可以使用以下方式構(gòu)建你的令牌:
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/上的調(diào)試器測試了每個令牌,它們似乎是等價的。在調(diào)試器中,十六進制值"12bd18f2cd12"的Base64編碼值是"Er0Y8s0S"。