[英]How to generate JWS in R language
我嘗試為google-oauth2.0 ServiceAccount生成JWT。
我設置了標題和有效負載(聲明)。 但是當我嘗試用RSASHA256嘆氣base64header.base64claim時,我的簽名不正確。 我發現PKI包中只有一個函數可以使用指定的哈希函數與RSA簽名。
我怎么知道我的簽名不正確? 我找到了可以從輸入和私有KEY生成JWT的資源 。
所以我只能看到,R函數的結果與jwt.io簽名不同。 我用兩個JWT令牌測試了對https://www.googleapis.com/oauth2/v3/token的請求,並且jwt.io正在運行。
這部分是針對JWT標題的。
library(base64enc)
library(jsonlite)
library(PKI)
#JWT header set up
alg <- "RS256"
typ <- "JWT"
header <- list("alg" = alg, "typ" = typ)
h <- toJSON(header, auto_unbox=TRUE)
enc.header <- base64encode(charToRaw(h))
這部分是針對JWT索賠(有效載荷)
iss <- "165724828594-mkuchqogmjapbl7mpfn0e7f7o3qlrqsr@developer.gserviceaccount.com"
scope <- "https://www.googleapis.com/auth/analytics.readonly"
aud <- "https://www.googleapis.com/oauth2/v3/token"
iat <- as.integer(as.POSIXct(Sys.time()))
exp <- iat+3600
claim <- list("iss" = iss, "scope" = scope, "aud" = aud, "exp" = exp, "iat" = iat)
cl <- toJSON(claim, auto_unbox=TRUE)
enc.claim <- base64encode(charToRaw(cl))
這是我的問題。
y <- file("~/keys/euroset-test-70c2d0d4eed1.pem")
key <- PKI.load.key(y)
what <- paste(enc.header,enc.claim, sep=".")
JWS <- PKI.sign(what, key, "SHA256")
enc.sign <- base64encode(JWS)
JWT <- paste(what,enc.sign, sep=".")
JWT
有什么幫助嗎? 我已經堅持了JWS 4天了。(
最后我發現了一個問題所在。 它一直是關於base64encoding。 我檢查了正確和不正確的JWT並找到了一些模式。 不正確的一個在有效載荷和簽名中有"=="
,我已用""
替換它。 同樣在簽名中所有"/"
我用"_"
替換,所有"+"
用"-"
替換。 希望它會給出同樣問題的暗示。
https://github.com/hadley/httr/blob/master/R/oauth-server-side.R
這是獲取適用於某些Google API的令牌的代碼(但不適用於我需要的雲...如果你讓它工作,請告訴我)。 此外,httr oauth_service_token比編寫自己的更容易使用。
init_oauth_service_account <- function(endpoint, secrets, scope = NULL) {
signature <- jwt_signature(secrets, scope = scope)
res <- POST(endpoint$access, body = list(
grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer",
assertion = signature
), encode = "form")
stop_for_status(res)
content(res, type = "application/json")
}
...
jwt_base64 <- function(x) base64url(jwt_json(x))
jwt_json <- function(x) jsonlite::toJSON(x, auto_unbox = TRUE)
base64url <- function(x) {
if (is.character(x)) {
x <- charToRaw(x)
}
out <- chartr('+/', '-_', base64enc::base64encode(x))
gsub("=+$", "", out)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.