Skip to content

Branca in .NET

Scott Brady edited this page Sep 11, 2020 · 7 revisions

Branca is a simple token format for private systems. Tokens are protected using XChaCha20-Poly1305 for authenticated encryption and serialized using base62.

This library offers two ways to create Branca tokens in .NET, either by using basic, string-based payloads or by using JWT-style payloads and validation using Microsoft.IdentityModel.

Keys must be 32-bytes in length.

To read more about Branca tokens, check out:

Basic Usage

The simplest way to create a Branca token is to use the basic usage style. This allows you to use any payload and decrypt the token without any other validation.

Token Creation

var key = Convert.FromBase64String("SOtPXZGVht/Lhl13HDa7tIzWAUg7QaHEgz6XE/6f0ME=");
var handler = new BrancaTokenHandler();

string token = handler.CreateToken("Hello, world!", key);

Overloads exist for passing in the timestamp as a uint or a DateTimeOffset.

Token Decryption

var key = Convert.FromBase64String("SOtPXZGVht/Lhl13HDa7tIzWAUg7QaHEgz6XE/6f0ME=");
var handler = new BrancaTokenHandler();

BrancaToken decryptToken = handler.DecryptToken(token, key);

JWT Style Usage

To have Branca replace JWTs, while still keeping the same format as a JWT payload, you can continue to use the SecurityTokenDescriptor.

Token Creation

var key = Convert.FromBase64String("SOtPXZGVht/Lhl13HDa7tIzWAUg7QaHEgz6XE/6f0ME=");
var handler = new BrancaTokenHandler();

string token = handler.CreateToken(new SecurityTokenDescriptor
{
    Issuer = "me",
    Audience = "you",
    Expires = DateTime.UtcNow.AddMinutes(5),
    NotBefore = DateTime.UtcNow,
    Claims = new Dictionary<string, object> {{"sub", "123"}},
    EncryptingCredentials = new EncryptingCredentials(
        new SymmetricSecurityKey(key), ExtendedSecurityAlgorithms.XChaCha20Poly1305)
});

Token Validation

var key = Convert.FromBase64String("SOtPXZGVht/Lhl13HDa7tIzWAUg7QaHEgz6XE/6f0ME=");
var handler = new BrancaTokenHandler();

ClaimsPrincipal principal = handler.ValidateToken(
    token,
    new TokenValidationParameters
    {
        ValidIssuer = "me",
        ValidAudience = "you",
        TokenDecryptionKey = new SymmetricSecurityKey(key)
    }, out SecurityToken parsedToken);