Example #1
0
        public void Write_Valid(string token)
        {
            var       descriptor = _tokens.Descriptors[token];
            JwtWriter writer     = new JwtWriter();
            var       value      = writer.WriteToken(descriptor);

            var reader = new JwtReader(_keys.Jwks);
            var result = reader.TryReadToken(value, TokenValidationPolicy.NoValidation);

            Assert.Equal(TokenValidationStatus.Success, result.Status);

            var jwt = result.Token;

            if (!(descriptor is JwsDescriptor jwsPayload))
            {
                if (!(descriptor is JweDescriptor jwePayload))
                {
                    throw new Xunit.Sdk.IsNotTypeException(typeof(JwtDescriptor), descriptor);
                }

                jwsPayload = jwePayload.Payload;
            }

            Assert.NotNull(jwsPayload);

            Assert.Equal(jwsPayload.IssuedAt, jwt.IssuedAt);
            Assert.Equal(jwsPayload.ExpirationTime, jwt.ExpirationTime);
            Assert.Equal(jwsPayload.Issuer, jwt.Issuer);
            Assert.Equal(jwsPayload.Audiences?.FirstOrDefault(), jwt.Audiences?.FirstOrDefault());
            Assert.Equal(jwsPayload.JwtId, jwt.Id);
        }
        public void Encode_Decode(string enc, byte[] alg)
        {
            var writer = new JwtWriter();

            var descriptor = new JweDescriptor(_bobKey, (KeyManagementAlgorithm)alg, (EncryptionAlgorithm)enc)
            {
                Payload = new JwsDescriptor(_signingKey, SignatureAlgorithm.HS256)
                {
                    Payload = new JwtPayload
                    {
                        { "sub", "Alice" }
                    }
                }
            };

            var token = writer.WriteToken(descriptor);

            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignatureByDefault(_signingKey)
                         .WithDecryptionKey(_bobKey)
                         .Build();

            var result = Jwt.TryParse(token, policy, out var jwt);

            Assert.True(result);
            Assert.True(jwt.Payload.TryGetClaim("sub", out var sub));
            Assert.Equal("Alice", sub.GetString());
            jwt.Dispose();
        }
        public void Write_Valid(string token)
        {
            var       descriptor = _tokens.Descriptors[token];
            JwtWriter writer     = new JwtWriter();
            var       value      = writer.WriteToken(descriptor);

            var policy = new TokenValidationPolicyBuilder()
                         .WithDecryptionKeys(_keys.Jwks)
                         .IgnoreSignatureByDefault()
                         .Build();

            var result = Jwt.TryParse(value, policy, out var jwt);

            Assert.True(result);

            if (!(descriptor is JwsDescriptor jwsPayload))
            {
                if (!(descriptor is JweDescriptor jwePayload))
                {
                    throw new Xunit.Sdk.IsNotTypeException(typeof(JwtDescriptor), descriptor);
                }

                jwsPayload = jwePayload.Payload;
            }

            Assert.NotNull(jwsPayload);
            if (jwsPayload.Payload.Count > 0)
            {
                Assert.True(jwt.Payload.TryGetClaim("iat", out var iat));
                Assert.True(jwt.Payload.TryGetClaim("exp", out var exp));
                Assert.True(jwt.Payload.TryGetClaim("iss", out var iss));
                Assert.True(jwt.Payload.TryGetClaim("aud", out var aud));
                Assert.True(jwt.Payload.TryGetClaim("jti", out var jti));
            }
        }
        private static JwsWrapper CreateDescriptor(SignatureAlgorithm algorithm)
        {
            var jwk = algorithm.Category switch
            {
                Cryptography.AlgorithmCategory.None => Jwk.None,
                Cryptography.AlgorithmCategory.EllipticCurve => ECJwk.GeneratePrivateKey(algorithm),
                Cryptography.AlgorithmCategory.Rsa => RsaJwk.GeneratePrivateKey(4096, algorithm),
                Cryptography.AlgorithmCategory.Aes => SymmetricJwk.GenerateKey(algorithm),
                Cryptography.AlgorithmCategory.AesGcm => SymmetricJwk.GenerateKey(algorithm),
                Cryptography.AlgorithmCategory.Hmac => SymmetricJwk.GenerateKey(algorithm),
                _ => throw new InvalidOperationException()
            };

            var descriptor = new JwsDescriptor(jwk, algorithm)
            {
                Payload = new JwtPayload
                {
                    { JwtClaimNames.Iat, EpochTime.UtcNow },
                    { JwtClaimNames.Exp, EpochTime.UtcNow + EpochTime.OneHour },
                    { JwtClaimNames.Iss, "https://idp.example.com/" },
                    { JwtClaimNames.Aud, "636C69656E745F6964" }
                }
            };
            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignature("https://idp.example.com/", jwk, algorithm)
                         .Build();


            var writer = new JwtWriter();

            return(new JwsWrapper(writer.WriteToken(descriptor), algorithm, policy));
        }
    }
        public void Compatible(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            var writer = new JwtWriter();

            foreach (var encryptionKey in SelectEncryptionKey(enc.Name.ToString(), alg.Name.ToString()))
            {
                var descriptor = new JweDescriptor(encryptionKey, alg, enc)
                {
                    Payload = new JwsDescriptor(_signingKey, SignatureAlgorithm.HS256)
                    {
                        Payload = new JwtPayload
                        {
                            { "sub", "Alice" }
                        }
                    }
                };

                var token = writer.WriteToken(descriptor);

                var policy = new TokenValidationPolicyBuilder()
                             .RequireSignatureByDefault(_signingKey)
                             .WithDecryptionKeys(_keys.Jwks)
                             .Build();

                var result = Jwt.TryParse(token, policy, out var jwt);
                Assert.True(result);
                Assert.True(jwt.Payload.TryGetClaim("sub", out var sub));
                Assert.Equal("Alice", sub.GetString());
                jwt.Dispose();
            }
        }
Example #6
0
        public void Encode_Decode(string alg)
        {
            var(signingKey, validationKey) = SelectKeys(alg);
            var writer     = new JwtWriter();
            var descriptor = new JwsDescriptor(signingKey, (SignatureAlgorithm)alg)
            {
                Payload = new JwtPayload
                {
                    { "sub", "Alice" }
                }
            };

            var token = writer.WriteToken(descriptor);

            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignatureByDefault(validationKey, (SignatureAlgorithm)alg)
                         .Build();

            var result = Jwt.TryParse(token, policy, out var jwt);

            Assert.True(result);
            Assert.True(jwt.Payload.TryGetClaim("sub", out var sub));
            Assert.Equal("Alice", sub.GetString());
            jwt.Dispose();
        }
Example #7
0
        public void Encode_Decode(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            var writer        = new JwtWriter();
            var encryptionKey = SelectKey(enc.Name, alg.Name);

            var descriptor = new JweDescriptor
            {
                EncryptionKey       = encryptionKey,
                EncryptionAlgorithm = enc,
                Algorithm           = alg,
                Payload             = new JwsDescriptor
                {
                    SigningKey = _signingKey,
                    Algorithm  = SignatureAlgorithm.HmacSha256,
                    Subject    = "Alice"
                }
            };

            var token = writer.WriteToken(descriptor);

            var reader = new JwtReader(encryptionKey);
            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignature(_signingKey)
                         .Build();

            var result = reader.TryReadToken(token, policy);

            Assert.Equal(TokenValidationStatus.Success, result.Status);
            Assert.Equal("Alice", result.Token.Subject);
        }
Example #8
0
 private static void Main()
 {
     Console.WriteLine("Starting...");
     writer.EnableHeaderCaching   = false;
     writer.IgnoreTokenValidation = false;
     using (var buffer = new PooledByteBufferWriter())
     {
         while (true)
         {
             writer.WriteToken(jwsDescriptor, buffer);
         }
     }
 }
Example #9
0
        public void Encode_Decode_NotSupported()
        {
            var writer = new JwtWriter();

            var descriptor = new JweDescriptor(Jwk.None, KeyManagementAlgorithm.Dir, new EncryptionAlgorithm(AlgorithmId.Undefined, "unsupported", 0, SignatureAlgorithm.None, 0, EncryptionType.NotSupported))
            {
                Payload = new JwsDescriptor(_signingKey, SignatureAlgorithm.HS256)
                {
                    Payload = new JwtPayload
                    {
                        { "sub", "Alice" }
                    }
                }
            };

            Assert.Throws <NotSupportedException>(() =>
            {
                var token = writer.WriteToken(descriptor);
            });
        }
Example #10
0
        private static byte[] Encode6(JwtWriter writer)
        {
            JweDescriptor descriptor = new JweDescriptor(encryptionKey1, KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A256Gcm)
            {
                Payload = new JwsDescriptor(signingKey3, SignatureAlgorithm.RS256)
                {
                    Payload = new JwtPayload
                    {
                        { JwtClaimNames.Iat, 1500000000L },
                        { JwtClaimNames.Exp, 2000000000L },
                        { JwtClaimNames.Iss, "https://idp.example.com/" },
                        { JwtClaimNames.Aud, "636C69656E745F6964" },
                        { JwtClaimNames.Sub, "*****@*****.**" },
                        { JwtClaimNames.Jti, "12345667890" }
                    }
                }
            };

            return(writer.WriteToken(descriptor));
        }
Example #11
0
        public void Encode_Decode_NotSupported()
        {
            var writer = new JwtWriter();

            var descriptor = new JweDescriptor
            {
                EncryptionAlgorithm = new EncryptionAlgorithm(-99, "unsupported", 0, SignatureAlgorithm.None, 0, EncryptionType.Undefined),
                Algorithm           = KeyManagementAlgorithm.Direct,
                Payload             = new JwsDescriptor
                {
                    SigningKey = _signingKey,
                    Algorithm  = SignatureAlgorithm.HmacSha256,
                    Subject    = "Alice"
                }
            };

            Assert.Throws <NotSupportedException>(() =>
            {
                var token = writer.WriteToken(descriptor);
            });
        }
Example #12
0
        public void Write_Binary()
        {
            var data = new byte[256];

            FillData(data);
            var key = new RsaJwk
                      (
                n: "sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw",
                e: "AQAB",
                d: "VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-rynq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-KyvjT1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ",
                p: "9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEPkrdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_biaBgelNgbC95sM",
                q: "uKlCKvKv_ZJMVcdIs5vVSU_6cPtYI1ljWytExV_skstvRSNi9r66jdd9-yBhVfuG4shsp2j7rGnIio901RBeHo6TPKWVVykPu1iYhQXw1jIABfw-MVsN-3bQ76WLdt2SDxsHs7q7zPyUyHXmps7ycZ5c72wGkUwNOjYelmkiNS0",
                dp: "w0kZbV63cVRvVX6yk3C8cMxo2qCM4Y8nsq1lmMSYhG4EcL6FWbX5h9yuvngs4iLEFk6eALoUS4vIWEwcL4txw9LsWH_zKI-hwoReoP77cOdSL4AVcraHawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs",
                dq: "o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU",
                qi: "eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlCtUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZB9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo"
                      )
            {
                Alg = KeyManagementAlgorithm.RsaPkcs1.Utf8Name
            };

            var descriptor = new BinaryJweDescriptor(data);

            descriptor.EncryptionKey       = key;
            descriptor.EncryptionAlgorithm = EncryptionAlgorithm.Aes128CbcHmacSha256;
            descriptor.Algorithm           = KeyManagementAlgorithm.RsaPkcs1;

            JwtWriter writer = new JwtWriter();
            var       value  = writer.WriteToken(descriptor);

            Assert.NotNull(value);

            var reader = new JwtReader(key);
            var result = reader.TryReadToken(value, TokenValidationPolicy.NoValidation);

            Assert.Equal(TokenValidationStatus.Success, result.Status);

            var jwt = result.Token;

            Assert.Equal(data, jwt.Binary);
        }
Example #13
0
        public void Write_Utf8ToEscape()
        {
            var plaintext = "Live long and prosper!€";

            var descriptor = new PlaintextJweDescriptor(plaintext);

            descriptor.EncryptionKey       = RsaKey;
            descriptor.EncryptionAlgorithm = EncryptionAlgorithm.Aes128CbcHmacSha256;
            descriptor.Algorithm           = KeyManagementAlgorithm.RsaPkcs1;

            JwtWriter writer = new JwtWriter();
            var       value  = writer.WriteToken(descriptor);

            var reader = new JwtReader(RsaKey);
            var result = reader.TryReadToken(value, TokenValidationPolicy.NoValidation);

            Assert.Equal(TokenValidationStatus.Success, result.Status);

            var jwt = result.Token;

            Assert.Equal(plaintext, jwt.Plaintext);
        }
        public void Write_Utf8ToEscape()
        {
            var plaintext = "Live long and prosper!€";

            var descriptor = new PlaintextJweDescriptor(RsaKey, KeyManagementAlgorithm.Rsa1_5, EncryptionAlgorithm.A128CbcHS256);

            descriptor.Payload = plaintext;

            JwtWriter writer = new JwtWriter();
            var       value  = writer.WriteToken(descriptor);

            var policy = new TokenValidationPolicyBuilder()
                         .WithDecryptionKey(RsaKey)
                         .IgnoreSignatureByDefault()
                         .Build();

            var result = Jwt.TryParse(value, policy, out var jwt);

            Assert.True(result);

            Assert.Equal(plaintext, jwt.Plaintext);
        }
        private static JweWrapper CreateDescriptor(KeyManagementAlgorithm algorithm, EncryptionAlgorithm encryptionAlgorithm)
        {
            var jwk = algorithm.Category switch
            {
                Cryptography.AlgorithmCategory.None => Jwk.None,
                Cryptography.AlgorithmCategory.EllipticCurve => ECJwk.GeneratePrivateKey(EllipticalCurve.P256, algorithm),
                Cryptography.AlgorithmCategory.Rsa => RsaJwk.GeneratePrivateKey(4096, algorithm),
                Cryptography.AlgorithmCategory.Aes => SymmetricJwk.GenerateKey(algorithm),
                Cryptography.AlgorithmCategory.AesGcm => SymmetricJwk.GenerateKey(algorithm),
                Cryptography.AlgorithmCategory.Hmac => SymmetricJwk.GenerateKey(algorithm),
                Cryptography.AlgorithmCategory.Direct => SymmetricJwk.GenerateKey(encryptionAlgorithm),
                Cryptography.AlgorithmCategory.Direct | Cryptography.AlgorithmCategory.EllipticCurve => ECJwk.GeneratePrivateKey(EllipticalCurve.P256),
                _ => throw new InvalidOperationException(algorithm.Category.ToString())
            };

            var descriptor = new JweDescriptor(jwk, algorithm, encryptionAlgorithm)
            {
                Payload = new JwsDescriptor(Jwk.None, SignatureAlgorithm.None)
                {
                    Payload = new JwtPayload
                    {
                        { JwtClaimNames.Iat, EpochTime.UtcNow },
                        { JwtClaimNames.Exp, EpochTime.UtcNow + EpochTime.OneHour },
                        { JwtClaimNames.Iss, "https://idp.example.com/" },
                        { JwtClaimNames.Aud, "636C69656E745F6964" }
                    }
                }
            };
            var policy = new TokenValidationPolicyBuilder()
                         .AcceptUnsecureToken("https://idp.example.com/")
                         .WithDecryptionKey(jwk)
                         .Build();

            var writer = new JwtWriter();

            return(new JweWrapper(writer.WriteToken(descriptor), algorithm, encryptionAlgorithm, policy));
        }
    }
Example #16
0
        public void Encode_Decode(string alg)
        {
            var(signingKey, validationKey) = SelectKeys(alg);
            var writer     = new JwtWriter();
            var descriptor = new JwsDescriptor
            {
                SigningKey = signingKey,
                Algorithm  = (SignatureAlgorithm)alg,
                Subject    = "Alice"
            };

            var token = writer.WriteToken(descriptor);

            var reader = new JwtReader();
            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignature(validationKey, (SignatureAlgorithm)alg)
                         .Build();

            var result = reader.TryReadToken(token, policy);

            Assert.Equal(TokenValidationStatus.Success, result.Status);
            Assert.Equal("Alice", result.Token.Subject);
        }
        public byte[] Encrypt()
        {
            var wrapper = Descriptors.JweWrappers[Alg][Enc];

            return(_writer.WriteToken(wrapper.Descriptor));
        }