Sapling Logo
SDK authentication quickstart

Rust JWT Generator

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

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

Rust 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.
Rust HS256 · sub + exp

This example uses the jsonwebtoken and serde crates.

use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use serde::Serialize;
use std::env;
use std::error::Error;
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Serialize)]
struct Claims {
    sub: String,
    exp: u64,
}

fn main() -> Result<(), Box<dyn Error>> {
    let public_key = env::var("SAPLING_PUBLIC_KEY")?;
    let private_key = env::var("SAPLING_PRIVATE_KEY")?;
    let expires_at = SystemTime::now()
        .duration_since(UNIX_EPOCH)?
        .as_secs()
        + 3600;

    let claims = Claims {
        sub: public_key,
        exp: expires_at,
    };
    let token = encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(private_key.as_bytes()),
    )?;

    println!("{token}");
    Ok(())
}
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 Rust

Rust is a programming language designed with comparable performance to C or C++, but with additional emphasis on code safety. Rust compilers do additional object reference and thread safety checks to prevent references to invalid memory or concurrency issues.