Sapling Logo
SDK authentication quickstart

Dart JWT Generator

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

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

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

This example uses dart_jsonwebtoken.

import 'dart:io';

import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';

void main() {
  final publicKey = Platform.environment['SAPLING_PUBLIC_KEY'];
  final privateKey = Platform.environment['SAPLING_PRIVATE_KEY'];
  if (publicKey == null || privateKey == null) {
    throw StateError(
      'Set SAPLING_PUBLIC_KEY and SAPLING_PRIVATE_KEY first.',
    );
  }

  final expiresAt =
      DateTime.now().add(const Duration(hours: 1)).millisecondsSinceEpoch ~/ 1000;
  final jwt = JWT({'sub': publicKey, 'exp': expiresAt});

  final token = jwt.sign(
    SecretKey(privateKey),
    algorithm: JWTAlgorithm.HS256,
  );
  print(token);
}
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 Dart

Dart is a programing language developed by Google. Applications in Dart are compiled to native code or JavaScript for cross-platform use on server, web, desktop and mobile applications. This is the language used by the cross-platform application framework Flutter.