R语言如何生成JWS

How to generate JWS in R language

我尝试为 google-oauth2.0 ServiceAccount 生成 JWT。

我设置了 header 和有效负载(声明)。但是当我尝试使用 RSASHA256 叹息 base64header.base64claim 时,我得到了不正确的签名。 我在 PKI 包中只发现了一个函数,它允许使用具有指定哈希函数的 RSA 对内容进行签名。

我怎么发现我的签名不正确?我发现 resource 可以从输入和私有 KEY 生成 JWT。

所以我所看到的是,我的 R 函数签名不同于 jwt.io 签名。 我已经用两个 JWT 令牌测试了对 https://www.googleapis.com/oauth2/v3/token 的请求,jwt.io 一个有效。

这部分用于 JWT header。

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 天了。(

终于找到问题所在了。 它一直是关于 base64 编码的。 我检查了 Correct 和 Inctorrect JWTs 并发现了一些模式。 不正确的一个在负载和签名中有 "==",我用 "" 替换了它。 同样在签名中,所有 "/" 我已替换为 "_",所有 "+" 已替换为 "-"。 希望能给遇到同样问题的人一个提示。

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