-
Notifications
You must be signed in to change notification settings - Fork 11
Branca in .NET
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:
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.
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
.
var key = Convert.FromBase64String("SOtPXZGVht/Lhl13HDa7tIzWAUg7QaHEgz6XE/6f0ME=");
var handler = new BrancaTokenHandler();
BrancaToken decryptToken = handler.DecryptToken(token, key);
To have Branca replace JWTs, while still keeping the same format as a JWT payload, you can continue to use the SecurityTokenDescriptor
.
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)
});
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);