Sapling Logo
SDK authentication quickstart

R JWT Generator

Sign a short-lived Sapling SDK credential in R without exposing your private API key to browser code.

  • HS256 signature
  • Server-side only
  • Public + private keys
SIGN R logo R HS256 · sub + exp

R JWT generator quickstart

Create a token with your public API key in the sub claim, a near-term Unix timestamp in exp, and an HS256 signature made with your private API key.

Sapling JWTs use HS256 with a sub claim containing your public API key and an exp claim containing a Unix timestamp. The examples use a one-hour lifetime; shorten it further when your application can refresh tokens easily.
R HS256 · sub + exp

This example uses the jsonlite and openssl packages.

library(jsonlite)
library(openssl)

base64url <- function(bytes) {
  encoded <- base64_encode(bytes)
  chartr("+/", "-_", sub("=+$", "", encoded))
}

public_key <- Sys.getenv("SAPLING_PUBLIC_KEY")
private_key <- Sys.getenv("SAPLING_PRIVATE_KEY")
if (!nzchar(public_key) || !nzchar(private_key)) {
  stop("Set SAPLING_PUBLIC_KEY and SAPLING_PRIVATE_KEY first.")
}

header <- toJSON(
  list(alg = "HS256", typ = "JWT"),
  auto_unbox = TRUE
)
claims <- toJSON(
  list(
    sub = public_key,
    exp = floor(as.numeric(Sys.time())) + 3600
  ),
  auto_unbox = TRUE
)

signing_input <- paste(
  base64url(charToRaw(header)),
  base64url(charToRaw(claims)),
  sep = "."
)
signature <- sha256(
  charToRaw(signing_input),
  key = charToRaw(private_key)
)

cat(signing_input, base64url(signature), sep = ".")
Generated token text/plain
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.<base64url-claims>.<signature>

Return the compact token to the browser and pass it to Sapling.init as the key. Issue a fresh token after it expires; never send the private key.

About R

R is a programming language and environment for statistical computing, data analysis, and visualization. It is widely used by data scientists, researchers, and teams working with quantitative data.