コード例 #1
0
        private static void JWT测试()
        {
            Console.WriteLine("--------JWT测试---------");

            // 申请一个密钥
            var key = JwtBuilder.GenerateKey("_elong.tech@2020_");

            Stopwatch t = new Stopwatch();

            t.Start();

            // 颁发令牌
            var token = new JwtBuilder()
                        .WithAes(true)
                        .WithAlgorithm(JwtSecurityAlgorithms.HmacSha256)
                        .WithSecret(key)
                        .AddClaim(JwtClaimNames.ExpirationTime, 60) // 60秒过期
                        .AddClaim(nameof(Organization.OrganizationID), 100)
                        .AddClaim(nameof(Organization.OrganizationName), "集团")
                        .Build();

            Console.WriteLine($"颁发令牌,消耗{t.ElapsedMilliseconds}毫秒");
            t.Restart();

            // 解码令牌,返回字典
            var payload = new JwtBuilder()
                          .WithAes(true)
                          .WithAlgorithm(JwtSecurityAlgorithms.HmacSha256)
                          .WithSecret(key)
                          .Decode(token);

            Console.WriteLine($"解码令牌,返回字典,消耗{t.ElapsedMilliseconds}毫秒");
            t.Restart();

            // 解码令牌,返回对象
            var org = new JwtBuilder()
                      .WithAes(true)
                      .WithAlgorithm(JwtSecurityAlgorithms.HmacSha256)
                      .WithSecret(key)
                      .Decode <Organization>(token);

            Console.WriteLine($"解码令牌,返回对象,消耗{t.ElapsedMilliseconds}毫秒");
            t.Restart();

            // 解析令牌,返回指定的Claim
            var claim = new JwtBuilder()
                        .WithAes(true)
                        .WithAlgorithm(JwtSecurityAlgorithms.HmacSha256)
                        .WithSecret(key)
                        .Parse(token, JwtClaimNames.JwtId);

            Console.WriteLine($"解析令牌,返回Claim,JwtId: {claim}, 消耗{t.ElapsedMilliseconds}毫秒");
            t.Restart();

            // 验证令牌
            var msg = new JwtBuilder()
                      .WithAes(true)
                      .WithAlgorithm(JwtSecurityAlgorithms.HmacSha256)
                      .WithSecret(key)
                      .Verify(token);

            Console.WriteLine($"验证令牌,消耗{t.ElapsedMilliseconds}毫秒");
            t.Stop();
            Console.WriteLine("");
        }