Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active December 3, 2021 01:20
Show Gist options
  • Save relyky/33723697f0251c7e2630a176ba6c7314 to your computer and use it in GitHub Desktop.
Save relyky/33723697f0251c7e2630a176ba6c7314 to your computer and use it in GitHub Desktop.
JWT helper, jose-jwt 範例
record MyInfo
{
public string foo { get; set; }
public string bar { get; set; }
public decimal abc { get; set; }
}
var info = new MyInfo {
foo = "FOO 123.456",
bar = "我是中文字",
abc = 9876543210.1234m
};
var token = JwtHelper.SimpleEncode(info);
var payload = JwtHelper.SimpleDecode<MyInfo>(token);
using Jose;
using System;
using System.Linq;
using System.Text;
using System.Text.Json;
static class JwtHelper
{
static readonly byte[] key192 = { 131, 117, 87, 14, xxx, 150, 19, 75, 24, xxx, 159, 78, 90, 51, xxx, 159, 214, 186, 251, xxx, 207, 246, 142, 127 };
public static string SimpleEncode<TObject>(TObject payload)
{
string json = JsonSerializer.Serialize<TObject>(payload);
byte[] blob = Encoding.UTF8.GetBytes(json);
byte[] blobR = blob.Select(b => (byte)~b).ToArray();
string token = JWT.EncodeBytes(blobR, key192, JweAlgorithm.A192GCMKW, JweEncryption.A192GCM);
string tokenR = String.Join('.', token.Split('.').Reverse());
return tokenR;
}
public static TObject SimpleDecode<TObject>(string token)
{
string tokenR = String.Join('.', token.Split('.').Reverse());
byte[] blobR = JWT.DecodeBytes(tokenR, key192, JweAlgorithm.A192GCMKW, JweEncryption.A192GCM);
byte[] blob = blobR.Select(b => (byte)~b).ToArray();
string json = Encoding.UTF8.GetString(blob, 0, blob.Length);
TObject payload = JsonSerializer.Deserialize<TObject>(json);
return payload;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment