Sapling Logo
SDK authentication quickstart

C JWT Generator

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

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

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

This example uses libjwt.

#include <jwt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(void) {
  const char *public_key = getenv("SAPLING_PUBLIC_KEY");
  const char *private_key = getenv("SAPLING_PRIVATE_KEY");
  if (public_key == NULL || private_key == NULL) {
    fputs("Set SAPLING_PUBLIC_KEY and SAPLING_PRIVATE_KEY first.\n", stderr);
    return 1;
  }

  jwt_t *token = NULL;
  if (jwt_new(&token) != 0) {
    return 1;
  }

  const long expires_at = (long)time(NULL) + 3600;
  if (jwt_add_grant(token, "sub", public_key) != 0 ||
      jwt_add_grant_int(token, "exp", expires_at) != 0 ||
      jwt_set_alg(token, JWT_ALG_HS256,
                  (const unsigned char *)private_key,
                  strlen(private_key)) != 0) {
    jwt_free(token);
    return 1;
  }

  char *encoded = jwt_encode_str(token);
  if (encoded == NULL) {
    jwt_free(token);
    return 1;
  }

  puts(encoded);
  free(encoded);
  jwt_free(token);
  return 0;
}
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 C

The programming language C is well known for its performance and widespread usage across all platforms and systems for multiple decades.