PM> Install-Package LitJWT
2、使用:
// Get recommended-size random key. var key = HS256Algorithm.GenerateRandomRecommendedKey(); // Create encoder, JwtEncoder is thread-safe and recommend to store static/singleton. var encoder = new JwtEncoder(new HS256Algorithm(key)); // Encode with payload, expire, and use specify payload serializer. var token = encoder.Encode(new { foo = "pay", bar = "load" }, TimeSpan.FromMinutes(30)); // Create decoder, JwtDecoder is also thread-safe so recommend to store static/singleton. var decoder = new JwtDecoder(encoder.SignAlgorithm); // Decode and verify, you can check the result. var result = decoder.TryDecode(token, out var payload); if (result == DecodeResult.Success) { Console.WriteLine((payload.foo, payload.bar)); }
自定义序列化:
var token = encoder.Encode(new PayloadSample { foo = "pay", bar = "load" }, TimeSpan.FromMinutes(30), (x, writer) => writer.Write(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(x))));
解码方法接收delegate T PayloadParser<T>(ReadOnlySpan<byte> payload)
。ReadOnlySpan<byte>
是utf8 json。基于 utf8 的序列化是最好的,虽然也可以使用 JSON.NET(但有编码损失)。
var result = decoder.TryDecode(token, x => JsonConvert.DeserializeObject<PayloadSample>(Encoding.UTF8.GetString(x)), out var payload);