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 System.IdentityModel.Tokens.Jwt.

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

var publicKey = Environment.GetEnvironmentVariable("SAPLING_PUBLIC_KEY")
    ?? throw new InvalidOperationException("Set SAPLING_PUBLIC_KEY first.");
var privateKey = Environment.GetEnvironmentVariable("SAPLING_PRIVATE_KEY")
    ?? throw new InvalidOperationException("Set SAPLING_PRIVATE_KEY first.");

var credentials = new SigningCredentials(
    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(privateKey)),
    SecurityAlgorithms.HmacSha256);

var descriptor = new SecurityTokenDescriptor {
    Subject = new ClaimsIdentity(new[] {
        new Claim(JwtRegisteredClaimNames.Sub, publicKey),
    }),
    Expires = DateTime.UtcNow.AddHours(1),
    SigningCredentials = credentials,
};

var handler = new JwtSecurityTokenHandler();
var token = handler.CreateToken(descriptor);
Console.WriteLine(handler.WriteToken(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 C#

C# is an object-oriented programming language for the Microsoft Windows platform. It is the primary language used for development inside the Windows ecosystem along with the .NET Framework and Visual Studio. This is also the language used by the cross-platform application framework Xamarin.