Пример #1
0
        public void GetSets()
        {
            var samlSecurityTokenHandler = new Saml2SecurityTokenHandler();
            var context = new GetSetContext
            {
                PropertyNamesAndSetGetValue = new List <KeyValuePair <string, List <object> > >
                {
                    new KeyValuePair <string, List <object> >("MaximumTokenSizeInBytes", new List <object> {
                        (object)TokenValidationParameters.DefaultMaximumTokenSizeInBytes, (object)1000, (object)10
                    }),
                    new KeyValuePair <string, List <object> >("SetDefaultTimesOnTokenCreation", new List <object> {
                        true, false, true
                    }),
                    new KeyValuePair <string, List <object> >("TokenLifetimeInMinutes", new List <object> {
                        (object)60, (object)1000, (object)10
                    }),
                },
                Object = samlSecurityTokenHandler
            };

            TestUtilities.GetSet(context);

            samlSecurityTokenHandler = new Saml2SecurityTokenHandler();
            TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)0, ExpectedException.ArgumentOutOfRangeException("IDX10101:"), context);
            TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)1, ExpectedException.NoExceptionExpected, context);
            TestUtilities.SetGet(samlSecurityTokenHandler, "Serializer", null, ExpectedException.ArgumentNullException(), context);

            TestUtilities.AssertFailIfErrors("Saml2SecurityTokenHandlerTests_GetSets", context.Errors);
        }
Пример #2
0
        public void GetSets()
        {
            var authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage()
            {
                IssuerAddress = "http://www.gotjwt.com"
            };

            var properties = new List <string>()
            {
                "IssuerAddress",
                "PostTitle",
                "ScriptButtonText",
                "ScriptDisabledText",
            };

            var context = new GetSetContext();

            foreach (string property in properties)
            {
                TestUtilities.SetGet(authenticationProtocolMessage, property, null, ExpectedException.ArgumentNullException(substringExpected: "value"), context);
                TestUtilities.SetGet(authenticationProtocolMessage, property, property, ExpectedException.NoExceptionExpected, context);
                TestUtilities.SetGet(authenticationProtocolMessage, property, "    ", ExpectedException.NoExceptionExpected, context);
                TestUtilities.SetGet(authenticationProtocolMessage, property, "\t\n\r", ExpectedException.NoExceptionExpected, context);
            }

            TestUtilities.AssertFailIfErrors(context.Errors);
        }
        public void GetDocuments()
        {
            FileDocumentRetriever docRetriever = new FileDocumentRetriever();

            GetDocument(null, docRetriever, CancellationToken.None, ExpectedException.ArgumentNullException());
            GetDocument("OpenIdConnectMetadata.json", docRetriever, CancellationToken.None, ExpectedException.IOException("IDX10804:", typeof(FileNotFoundException), "IDX10814:"));
            GetDocument("ValidJson.json", docRetriever, CancellationToken.None, ExpectedException.NoExceptionExpected);
        }
 public async Task FromNetwork()
 {
     OpenIdConnectConfiguration configuration = await GetConfigurationFromHttpAsync(OpenIdConfigData.AADCommonUrl, expectedException: ExpectedException.NoExceptionExpected);
     Assert.NotNull(configuration);
     
     await GetConfigurationFromHttpAsync(string.Empty, expectedException: ExpectedException.ArgumentNullException());
     await GetConfigurationFromHttpAsync(OpenIdConfigData.BadUri, expectedException: ExpectedException.ArgumentException("IDX20108:"));
     await GetConfigurationFromHttpAsync(OpenIdConfigData.HttpsBadUri, expectedException: ExpectedException.IOException(inner: typeof(HttpRequestException)));
 }
Пример #5
0
        public void Publics()
        {
            HttpDocumentRetriever docRetriever = new HttpDocumentRetriever();

            GetDocument(null, docRetriever, ExpectedException.ArgumentNullException());
            GetDocument("OpenIdConnectMetadata.json", docRetriever, new ExpectedException(typeof(ArgumentException), "IDX10108:"));
            GetDocument("httpss://OpenIdConnectMetadata.json", docRetriever, new ExpectedException(typeof(ArgumentException), "IDX10108:"));
            GetDocument("HTTPS://login.windows.net/common/.well-known/openid-configuration", docRetriever, ExpectedException.NoExceptionExpected);
            GetDocument("https://login.windows.net/common/.well-known/openid-configuration", docRetriever, ExpectedException.NoExceptionExpected);
            docRetriever.RequireHttps = false;
            GetDocument("OpenIdConnectMetadata.json", docRetriever, new ExpectedException(typeof(IOException), "IDX10804:", typeof(InvalidOperationException)));
        }
        public void Constructors()
        {
            OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage();

            Assert.Equal(openIdConnectMessage.IssuerAddress, string.Empty);
            openIdConnectMessage = new OpenIdConnectMessage()
            {
                IssuerAddress = "http://www.got.jwt.com"
            };
            Assert.Equal(openIdConnectMessage.IssuerAddress, "http://www.got.jwt.com");
            ExpectedException expectedException = ExpectedException.NoExceptionExpected;
            string            json    = @"{""response_mode"":""responseMode"", ""response_type"":""responseType"", ""refresh_token"":""refreshToken""}";
            string            badJson = @"{""response_mode"":""responseMode"";""respone_mode"":""badResponeMode""}";

            // null stirng json
            expectedException = ExpectedException.ArgumentNullException();
            TestJsonStringConstructor((string)null, expectedException);

            // bad string json
            expectedException = ExpectedException.ArgumentException("IDX10106");
            TestJsonStringConstructor(badJson, expectedException);

            // no exception, well-formed json
            expectedException    = ExpectedException.NoExceptionExpected;
            openIdConnectMessage = TestJsonStringConstructor(json, expectedException);
            Assert.True(openIdConnectMessage.RefreshToken.Equals("refreshToken"), "openIdConnectMessage.RefreshToken does not match expected value: refreshToken");
            Assert.True(openIdConnectMessage.ResponseMode.Equals("responseMode"), "openIdConnectMessage.ResponseMode does not match expected value: refreshToken");
            Assert.True(openIdConnectMessage.ResponseType.Equals("responseType"), "openIdConnectMessage.ResponseType does not match expected value: refreshToken");
            Assert.True(openIdConnectMessage.ClientId == null, "openIdConnectMessage.ClientId is not null");

            // no exception, using JObject ctor
            expectedException = ExpectedException.NoExceptionExpected;
            try
            {
                openIdConnectMessage = new OpenIdConnectMessage(JObject.Parse(json));
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            Assert.True(openIdConnectMessage.RefreshToken.Equals("refreshToken"), "openIdConnectMessage.RefreshToken does not match expected value: refreshToken");
            Assert.True(openIdConnectMessage.ResponseMode.Equals("responseMode"), "openIdConnectMessage.ResponseMode does not match expected value: refreshToken");
            Assert.True(openIdConnectMessage.ResponseType.Equals("responseType"), "openIdConnectMessage.ResponseType does not match expected value: refreshToken");
            Assert.True(openIdConnectMessage.ClientId == null, "openIdConnectMessage.ClientId is not null");

            // test with an empty JObject
            openIdConnectMessage = new OpenIdConnectMessage(new JObject());
        }
Пример #7
0
 public static TheoryData <OpenIdConnectMessageTheoryData> ConstructorsTheoryData()
 {
     return(new TheoryData <OpenIdConnectMessageTheoryData>
     {
         new OpenIdConnectMessageTheoryData
         {
             First = true,
             ExpectedException = ExpectedException.ArgumentNullException("IDX10000:"),
             Json = "",
             TestId = "empty string"
         },
         new OpenIdConnectMessageTheoryData
         {
             ExpectedException = ExpectedException.ArgumentNullException("IDX10000:"),
             TestId = "null string"
         },
         new OpenIdConnectMessageTheoryData
         {
             ExpectedException = ExpectedException.ArgumentNullException("IDX10000:"),
             Json = @"{""response_mode"":""responseMode"", ""response_type"":""responseType"", ""refresh_token"":""refreshToken""}",
             TestId = "null jobject"
         },
         new OpenIdConnectMessageTheoryData
         {
             ExpectedException = ExpectedException.ArgumentException("IDX21106"),
             Json = @"{""response_mode"":""responseMode"";""respone_mode"":""duplicateResponeMode""}",
             TestId = "ResponseMode duplicated"
         },
         new OpenIdConnectMessageTheoryData
         {
             JObject = new JObject(),
             Json = "{}",
             Message = new OpenIdConnectMessage(),
             TestId = "empty json string, empty jobj"
         },
         new OpenIdConnectMessageTheoryData
         {
             JObject = JObject.Parse(@"{""response_mode"":""responseMode"", ""response_type"":""responseType"", ""refresh_token"":""refreshToken""}"),
             Json = @"{""response_mode"":""responseMode"", ""response_type"":""responseType"", ""refresh_token"":""refreshToken""}",
             Message = new OpenIdConnectMessage
             {
                 RefreshToken = "refreshToken",
                 ResponseMode = "responseMode",
                 ResponseType = "responseType"
             },
             TestId = "ValidJson"
         }
     });
 }
        public static TheoryData <JwtTheoryData> InvalidNumberOfSegmentsData(string errorString, TheoryData <JwtTheoryData> theoryData)
        {
            theoryData.Add(new JwtTheoryData
            {
                CanRead           = false,
                ExpectedException = ExpectedException.ArgumentNullException(),
                TestId            = "null"
            });

            theoryData.Add(new JwtTheoryData
            {
                CanRead           = false,
                ExpectedException = ExpectedException.ArgumentNullException(),
                TestId            = "emptystring",
                Token             = ""
            });
            theoryData.Add(new JwtTheoryData
            {
                CanRead           = false,
                ExpectedException = ExpectedException.ArgumentException(errorString),
                TestId            = "a",
                Token             = "a"
            });
            theoryData.Add(new JwtTheoryData
            {
                CanRead           = false,
                ExpectedException = ExpectedException.ArgumentException(errorString),
                TestId            = "a.b",
                Token             = "a.b"
            });
            theoryData.Add(new JwtTheoryData
            {
                CanRead           = false,
                ExpectedException = ExpectedException.ArgumentException(errorString),
                TestId            = "a.b.c.d",
                Token             = "a.b.c.d"
            });
            theoryData.Add(new JwtTheoryData
            {
                CanRead           = false,
                ExpectedException = ExpectedException.ArgumentException(errorString),
                TestId            = "a.b.c.d.e.f",
                Token             = "a.b.c.d.e.f"
            });

            return(theoryData);
        }
Пример #9
0
        public void Publics( )
        {
            var signature  = new Signature();
            var properties = new List <string>()
            {
                "SignatureValue",
                "SignedInfo",
            };

            var context = new GetSetContext( );

            foreach (string property in properties)
            {
                TestUtilities.SetGet(signature, property, null, ExpectedException.ArgumentNullException(substringExpected: "value"), context);
            }

            TestUtilities.AssertFailIfErrors($"{this}.Publics", context.Errors);
        }
        public static TheoryData <string, string, ExpectedException> InvalidNumberOfSegmentsData(string errorString)
        {
            var dataSet = new TheoryData <string, string, ExpectedException>();

            dataSet.Add(
                "Test1",
                null,
                ExpectedException.ArgumentNullException()
                );

            dataSet.Add(
                "Test2",
                "",
                ExpectedException.ArgumentNullException()
                );

            dataSet.Add(
                "Test3",
                "a",
                ExpectedException.ArgumentException(errorString)
                );

            dataSet.Add(
                "Test4",
                "a.b",
                ExpectedException.ArgumentException(errorString)
                );

            dataSet.Add(
                "Test5",
                "a.b.c.d",
                ExpectedException.ArgumentException(errorString)
                );

            dataSet.Add(
                "Test6",
                "a.b.c.d.e.f",
                ExpectedException.ArgumentException(errorString)
                );

            return(dataSet);
        }
Пример #11
0
        public void Constructors()
        {
            WsFederationMessage wsFederationMessage = new WsFederationMessage();

            Assert.AreEqual(wsFederationMessage.IssuerAddress, string.Empty);

            wsFederationMessage = new WsFederationMessage("http://www.got.jwt.com");
            Assert.AreEqual(wsFederationMessage.IssuerAddress, "http://www.got.jwt.com");

            ExpectedException expectedException = ExpectedException.ArgumentNullException("issuerAddress");

            try
            {
                wsFederationMessage = new WsFederationMessage((string)null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }
        }
Пример #12
0
        public void CreateTokenNegativeCases()
        {
            var errors  = new List <string>();
            var handler = new JwtSecurityTokenHandler();
            var ee      = ExpectedException.ArgumentNullException("tokenDescriptor");

            try
            {
                handler.CreateEncodedJwt((SecurityTokenDescriptor)null);
                ee.ProcessNoException(errors);
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex, errors);
            }

            try
            {
                handler.CreateJwtSecurityToken((SecurityTokenDescriptor)null);
                ee.ProcessNoException(errors);
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex, errors);
            }

            try
            {
                handler.CreateToken((SecurityTokenDescriptor)null);
                ee.ProcessNoException(errors);
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex, errors);
            }

            TestUtilities.AssertFailIfErrors(errors);
        }
        public void GetSets()
        {
            AuthenticationProtocolMessage authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage()
            {
                IssuerAddress = "http://www.gotjwt.com"
            };

            List <string> properties = new List <string>()
            {
                "IssuerAddress",
                "PostTitle",
                "ScriptButtonText",
                "ScriptDisabledText",
            };

            foreach (string property in properties)
            {
                TestUtilities.SetGet(authenticationProtocolMessage, property, null, ExpectedException.ArgumentNullException(substringExpected: "value"));
                TestUtilities.SetGet(authenticationProtocolMessage, property, property, ExpectedException.NoExceptionExpected);
                TestUtilities.SetGet(authenticationProtocolMessage, property, "    ", ExpectedException.NoExceptionExpected);
                TestUtilities.SetGet(authenticationProtocolMessage, property, "\t\n\r", ExpectedException.NoExceptionExpected);
            }
        }
        private void ValidateIssuer()
        {
            DerivedSamlSecurityTokenHandler samlSecurityTokenHandler = new DerivedSamlSecurityTokenHandler();

            ExpectedException expectedException = ExpectedException.NoExceptionExpected;

            ValidateIssuer(null, new TokenValidationParameters {
                ValidateIssuer = false
            }, samlSecurityTokenHandler, expectedException);

            expectedException = ExpectedException.ArgumentNullException(substringExpected: "Parameter name: validationParameters");
            ValidateIssuer("bob", null, samlSecurityTokenHandler, expectedException);

            expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10204");
            ValidateIssuer("bob", new TokenValidationParameters {
            }, samlSecurityTokenHandler, expectedException);

            expectedException = ExpectedException.NoExceptionExpected;
            string issuer = ValidateIssuer("bob", new TokenValidationParameters {
                ValidIssuer = "bob"
            }, samlSecurityTokenHandler, expectedException);

            Assert.IsTrue(issuer == "bob", "issuer mismatch");

            expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205");
            ValidateIssuer("bob", new TokenValidationParameters {
                ValidIssuer = "frank"
            }, samlSecurityTokenHandler, expectedException);

            List <string> validIssuers = new List <string> {
                "john", "paul", "george", "ringo"
            };

            expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205");
            ValidateIssuer("bob", new TokenValidationParameters {
                ValidIssuers = validIssuers
            }, samlSecurityTokenHandler, expectedException);

            expectedException = ExpectedException.NoExceptionExpected;
            ValidateIssuer("bob", new TokenValidationParameters {
                ValidateIssuer = false
            }, samlSecurityTokenHandler, expectedException);

            validIssuers.Add("bob");
            expectedException = ExpectedException.NoExceptionExpected;
            issuer            = ValidateIssuer("bob", new TokenValidationParameters {
                ValidIssuers = validIssuers
            }, samlSecurityTokenHandler, expectedException);
            Assert.IsTrue(issuer == "bob", "issuer mismatch");

            expectedException = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10204");
            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                IssuerValidator  = IdentityUtilities.IssuerValidatorEcho,
            };

            ValidateIssuer("bob", validationParameters, samlSecurityTokenHandler, expectedException);

            // no delegate secondary should still succeed
            expectedException    = ExpectedException.NoExceptionExpected;
            validationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidIssuers     = validIssuers,
            };

            issuer = ValidateIssuer("bob", validationParameters, samlSecurityTokenHandler, expectedException);
            Assert.IsTrue(issuer == "bob", "issuer mismatch");

            // no delegate, secondary should fail
            validIssuers = new List <string> {
                "john", "paul", "george", "ringo"
            };
            expectedException    = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205");
            validationParameters = new TokenValidationParameters
            {
                IssuerSigningKey = new X509SecurityKey(KeyingMaterial.DefaultCert_2048),
                ValidateAudience = false,
                ValidIssuer      = "http://Bob",
            };
            ValidateIssuer("bob", validationParameters, samlSecurityTokenHandler, expectedException);

            validationParameters.ValidateIssuer  = false;
            validationParameters.IssuerValidator = IdentityUtilities.IssuerValidatorThrows;
            ValidateIssuer("bob", validationParameters, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected);
        }
Пример #15
0
        public static void AddValidateAudienceTheoryData(List <TokenTheoryData> theoryData)
        {
            theoryData.Add(new TokenTheoryData
            {
                Audiences            = new List <string>(),
                First                = true,
                ExpectedException    = ExpectedException.ArgumentNullException("IDX10000:"),
                TestId               = "TokenValidationParameters null",
                ValidationParameters = null,
            });

            theoryData.Add(new TokenTheoryData
            {
                Audiences            = new List <string>(),
                TestId               = "ValidateAudience = false",
                ValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                },
            });

            theoryData.Add(new TokenTheoryData
            {
                Audiences            = new List <string>(),
                ExpectedException    = ExpectedException.SecurityTokenInvalidAudienceException("IDX10208:"),
                TestId               = "no audiences in validationParameters",
                ValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = true,
                },
            });

            theoryData.Add(new TokenTheoryData
            {
                Audiences = new List <string> {
                    "John"
                },
                ExpectedException    = ExpectedException.SecurityTokenInvalidAudienceException("IDX10208:"),
                TestId               = "audience has value, tvp has no values",
                ValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = true,
                },
            });

            theoryData.Add(new TokenTheoryData
            {
                Audiences = new List <string> {
                    "John"
                },
                ExpectedException    = ExpectedException.SecurityTokenInvalidAudienceException("IDX10214:"),
                TestId               = "audience not matched",
                ValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = true,
                    ValidAudience    = "frank"
                },
            });

            theoryData.Add(new TokenTheoryData
            {
                Audiences = new List <string> {
                    "John"
                },
                TestId = "AudienceValidator returns true",
                ValidationParameters = new TokenValidationParameters
                {
                    AudienceValidator = (aud, token, type) =>
                    {
                        return(true);
                    },
                    ValidateAudience = true,
                    ValidAudience    = "frank"
                },
            });

            theoryData.Add(new TokenTheoryData
            {
                Audiences = new List <string> {
                    "John"
                },
                TestId = "AudienceValidator throws, validateAudience false",
                ValidationParameters = new TokenValidationParameters
                {
                    AudienceValidator = ValidationDelegates.AudienceValidatorThrows,
                    ValidateAudience  = false,
                    ValidAudience     = "frank"
                },
            });
        }
Пример #16
0
        public void Constructors()
        {
            var context = new CompareContext {
                Title = "OpenIdConnectConfigurationTests.Constructors"
            };

            RunOpenIdConnectConfigurationTest((string)null, new OpenIdConnectConfiguration(), ExpectedException.ArgumentNullException(), context);
            RunOpenIdConnectConfigurationTest(OpenIdConfigData.JsonAllValues, OpenIdConfigData.FullyPopulated, ExpectedException.NoExceptionExpected, context);
            RunOpenIdConnectConfigurationTest(OpenIdConfigData.OpenIdConnectMetatadataBadJson, null, ExpectedException.ArgumentException(substringExpected: "IDX21815:", inner: typeof(JsonReaderException)), context);
            TestUtilities.AssertFailIfErrors(context);
        }
Пример #17
0
        public static void AddValidateIssuerTheoryData(List <TokenTheoryData> theoryData)
        {
            theoryData.Add(new TokenTheoryData
            {
                ExpectedException    = ExpectedException.ArgumentNullException("IDX10000:"),
                First                = true,
                Issuer               = "bob",
                TestId               = "ValidationParameters null",
                ValidationParameters = null,
            });

            theoryData.Add(new TokenTheoryData
            {
                TestId = "ValidateIssuer == false",
                ValidationParameters = new TokenValidationParameters {
                    ValidateIssuer = false
                },
            });

            theoryData.Add(new TokenTheoryData
            {
                ExpectedException    = ExpectedException.SecurityTokenInvalidIssuerException("IDX10205:"),
                Issuer               = "bob",
                TestId               = "Issuer not matched",
                ValidationParameters = new TokenValidationParameters {
                    ValidIssuer = "frank"
                }
            });

            theoryData.Add(new TokenTheoryData
            {
                Issuer = "bob",
                TestId = "Issuer matched",
                ValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidIssuer      = "bob"
                }
            });

            theoryData.Add(new TokenTheoryData
            {
                ExpectedException    = ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205:"),
                Issuer               = "bob",
                TestId               = "ValidIssuers set but not matched",
                ValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    ValidIssuers     = new List <string> {
                        "john", "paul", "george", "ringo"
                    }
                }
            });

            theoryData.Add(new TokenTheoryData
            {
                Issuer = "bob",
                TestId = "IssuerValidator - echo",
                ValidationParameters = new TokenValidationParameters
                {
                    IssuerValidator  = ValidationDelegates.IssuerValidatorEcho,
                    ValidateAudience = false
                }
            });
        }
        public static TheoryData <string, JwtSecurityTokenTestVariation, JwtSecurityTokenTestVariation, string, ExpectedException> EmbeddedTokenConstructorData()
        {
            var dataSet = new TheoryData <string, JwtSecurityTokenTestVariation, JwtSecurityTokenTestVariation, string, ExpectedException>();

            dataSet.Add("Embedded token all properties null",
                        // outer token
                        new JwtSecurityTokenTestVariation
            {
                RawHeader               = null,
                RawEncryptedKey         = null,
                RawInitializationVector = null,
                RawCiphertext           = null,
                RawAuthenticationTag    = null,
            },
                        // inner token
                        new JwtSecurityTokenTestVariation
            {
                Issuer             = null,
                Audience           = null,
                Claims             = null,
                SigningCredentials = null,
            },
                        String.Empty,
                        ExpectedException.ArgumentNullException()
                        );

            JwtSecurityTokenTestVariation innerToken = new JwtSecurityTokenTestVariation
            {
                NotBefore = DateTime.MinValue,
                Expires   = DateTime.UtcNow,
            };

            JwtSecurityTokenTestVariation outerValidJweDirect = CreateVariationOnToken(EncodedJwts.ValidJweDirect);

            dataSet.Add("ValidJweDirect- Construct by parts", outerValidJweDirect, innerToken, String.Empty, ExpectedException.NoExceptionExpected);
            dataSet.Add("ValidJweDirect- Construct by string", outerValidJweDirect, null, EncodedJwts.ValidJweDirect, ExpectedException.NoExceptionExpected);

            JwtSecurityTokenTestVariation outerValidJweDirect2 = CreateVariationOnToken(EncodedJwts.ValidJweDirect2);

            dataSet.Add("ValidJweDirect2- Construct by parts", outerValidJweDirect2, innerToken, String.Empty, ExpectedException.NoExceptionExpected);
            dataSet.Add("ValidJweDirect2- Construct by string", outerValidJweDirect2, null, EncodedJwts.ValidJweDirect2, ExpectedException.NoExceptionExpected);

            JwtSecurityTokenTestVariation outerValidJwe = CreateVariationOnToken(EncodedJwts.ValidJwe);

            dataSet.Add("ValidJwe- Construct by parts", outerValidJwe, innerToken, String.Empty, ExpectedException.NoExceptionExpected);
            dataSet.Add("ValidJwe- Construct by string", outerValidJwe, null, EncodedJwts.ValidJwe, ExpectedException.NoExceptionExpected);

            JwtSecurityTokenTestVariation outerValidJwe2 = CreateVariationOnToken(EncodedJwts.ValidJwe2);

            dataSet.Add("ValidJwe2- Construct by parts", outerValidJwe2, innerToken, String.Empty, ExpectedException.NoExceptionExpected);
            dataSet.Add("ValidJwe2- Construct by string", outerValidJwe2, null, EncodedJwts.ValidJwe2, ExpectedException.NoExceptionExpected);

            // Hand in a valid variation. We should fail before the variation is used.
            dataSet.Add("Invalid outer token 1- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe, ExpectedException.ArgumentException(substringExpected: "IDX12709"));
            dataSet.Add("Invalid outer token 2- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe2, ExpectedException.ArgumentException(substringExpected: "IDX12709"));
            dataSet.Add("Invalid outer token 3- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe3, ExpectedException.ArgumentException(substringExpected: "IDX12709"));
            dataSet.Add("Invalid outer token 4- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe4, ExpectedException.ArgumentException(substringExpected: "IDX12709"));
            dataSet.Add("Invalid outer token 5- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe5, ExpectedException.ArgumentException(substringExpected: "IDX12709"));
            dataSet.Add("Invalid outer token 6- Construct by string", outerValidJweDirect, null, EncodedJwts.InvalidJwe6, ExpectedException.ArgumentException(substringExpected: "IDX12709"));

            return(dataSet);
        }
        public void ValidateToken()
        {
            // parameter validation
            Saml2SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler();

            TestUtilities.ValidateToken(securityToken: null, validationParameters: new TokenValidationParameters(), tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentNullException(substringExpected: "name: securityToken"));
            TestUtilities.ValidateToken(securityToken: "s", validationParameters: null, tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentNullException(substringExpected: "name: validationParameters"));

            tokenHandler.MaximumTokenSizeInBytes = 1;
            TestUtilities.ValidateToken(securityToken: "ss", validationParameters: new TokenValidationParameters(), tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentException(substringExpected: "IDX10209"));

            tokenHandler.MaximumTokenSizeInBytes = TokenValidationParameters.DefaultMaximumTokenSizeInBytes;
            string samlToken = IdentityUtilities.CreateSaml2Token();

            TestUtilities.ValidateToken(samlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, tokenHandler, ExpectedException.NoExceptionExpected);

            // EncryptedAssertion
            SecurityTokenDescriptor tokenDescriptor =
                new SecurityTokenDescriptor
            {
                AppliesToAddress      = IdentityUtilities.DefaultAudience,
                EncryptingCredentials = new EncryptedKeyEncryptingCredentials(KeyingMaterial.DefaultAsymmetricCert_2048),
                Lifetime           = new Lifetime(DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(1)),
                SigningCredentials = KeyingMaterial.DefaultAsymmetricSigningCreds_2048_RsaSha2_Sha2,
                Subject            = IdentityUtilities.DefaultClaimsIdentity,
                TokenIssuerName    = IdentityUtilities.DefaultIssuer,
            };

            samlToken = IdentityUtilities.CreateSaml2Token(tokenDescriptor);
            TestUtilities.ValidateToken(samlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, tokenHandler, new ExpectedException(typeExpected: typeof(EncryptedTokenDecryptionFailedException), substringExpected: "ID4022"));

            TokenValidationParameters validationParameters = IdentityUtilities.DefaultAsymmetricTokenValidationParameters;

            validationParameters.TokenDecryptionKeys = new List <SecurityKey> {
                KeyingMaterial.DefaultX509Key_2048
            }.AsReadOnly();
            TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected);

            TestUtilities.ValidateTokenReplay(samlToken, tokenHandler, validationParameters);
            TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected);

            validationParameters.LifetimeValidator =
                (nb, exp, st, tvp) =>
            {
                return(false);
            };
            TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, new ExpectedException(typeExpected: typeof(SecurityTokenInvalidLifetimeException), substringExpected: "IDX10230:"));

            validationParameters.ValidateLifetime  = false;
            validationParameters.LifetimeValidator = IdentityUtilities.LifetimeValidatorThrows;
            TestUtilities.ValidateToken(securityToken: samlToken, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected);
        }
        public static TheoryData <TheoryParams> DecryptTokenTheoryData()
        {
            var theoryData = new TheoryData <TheoryParams>();

            var tokenHandler = new PublicJwtSecurityTokenHandler();

            // Parameter validation
            theoryData.Add(new TheoryParams("Test1", null, new TokenValidationParameters(), tokenHandler, ExpectedException.ArgumentNullException()));
            theoryData.Add(new TheoryParams("Test2", new JwtSecurityToken(), null, tokenHandler, ExpectedException.ArgumentNullException()));
            theoryData.Add(new TheoryParams("Test3", new JwtSecurityToken(), new TokenValidationParameters(), tokenHandler, ExpectedException.SecurityTokenException()));

            // Enc empty
            var header = new JwtHeader();

            header[JwtHeaderParameterNames.Enc] = "";
            theoryData.Add(new TheoryParams("Test4", new JwtSecurityToken(), new TokenValidationParameters(), tokenHandler, ExpectedException.SecurityTokenException()));

            // Alg empty
            header = new JwtHeader();
            header[JwtHeaderParameterNames.Enc] = SecurityAlgorithms.Aes128CbcHmacSha256;
            theoryData.Add(new TheoryParams("Test5", new JwtSecurityToken(), new TokenValidationParameters(), tokenHandler, ExpectedException.SecurityTokenException()));

            // Alg not supproted
            header = new JwtHeader();
            header[JwtHeaderParameterNames.Alg] = SecurityAlgorithms.Aes128KW;
            theoryData.Add(new TheoryParams("Test6", new JwtSecurityToken(), new TokenValidationParameters(), tokenHandler, ExpectedException.SecurityTokenException()));

            return(theoryData);
        }
Пример #21
0
        public void Publics()
        {
            string value1 = "value1";
            string value2 = "value2";
            string param1 = "param1";
            string param2 = "param2";

            AuthenticationProtocolMessage authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage()
            {
                IssuerAddress = "http://www.gotjwt.com"
            };
            ExpectedException expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");

            try
            {
                authenticationProtocolMessage.GetParameter(null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");
            try
            {
                authenticationProtocolMessage.RemoveParameter(null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            expectedException = ExpectedException.ArgumentNullException(substringExpected: "parameter");
            try
            {
                authenticationProtocolMessage.SetParameter(null, null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            authenticationProtocolMessage.SetParameter(param1, value1);
            authenticationProtocolMessage.RemoveParameter(param2);
            Assert.Equal(authenticationProtocolMessage.GetParameter(param1), value1);

            authenticationProtocolMessage.RemoveParameter(param1);
            Assert.Null(authenticationProtocolMessage.GetParameter(param1));

            authenticationProtocolMessage.SetParameter(param1, value1);
            authenticationProtocolMessage.SetParameter(param1, value2);
            authenticationProtocolMessage.SetParameter(param2, value2);
            authenticationProtocolMessage.SetParameter(param2, value1);

            Assert.Equal(authenticationProtocolMessage.GetParameter(param1), value2);
            Assert.Equal(authenticationProtocolMessage.GetParameter(param2), value1);

            authenticationProtocolMessage = new DerivedAuthenticationProtocolMessage()
            {
                IssuerAddress = "http://www.gotjwt.com"
            };
            authenticationProtocolMessage.SetParameter("bob", "     ");

            string queryString = authenticationProtocolMessage.BuildRedirectUrl();

            Assert.NotNull(queryString);
            Assert.Contains("bob", queryString);

            authenticationProtocolMessage.IssuerAddress = string.Empty;
            queryString = authenticationProtocolMessage.BuildRedirectUrl();
            Assert.NotNull(queryString);
        }
Пример #22
0
        public static TheoryData <JWEDecompressionTheoryData> JWEDecompressionTheoryData()
        {
            var compressionProviderFactoryForCustom = new CompressionProviderFactory()
            {
                CustomCompressionProvider = new SampleCustomCompressionProvider("MyAlgorithm")
            };

            var compressionProviderFactoryForCustom2 = new CompressionProviderFactory()
            {
                CustomCompressionProvider = new SampleCustomCompressionProviderDecompressAndCompressAlwaysFail("MyAlgorithm")
            };

            return(new TheoryData <JWEDecompressionTheoryData>()
            {
                new JWEDecompressionTheoryData
                {
                    ValidationParameters = Default.JWECompressionTokenValidationParameters,
                    JWECompressionString = ReferenceTokens.JWECompressionTokenWithDEF,
                    CompressionProviderFactory = CompressionProviderFactory.Default,
                    TestId = "ValidAlgorithm"
                },
                new JWEDecompressionTheoryData
                {
                    ValidationParameters = Default.JWECompressionTokenValidationParameters,
                    JWECompressionString = ReferenceTokens.JWECompressionTokenWithUnsupportedAlgorithm,
                    CompressionProviderFactory = CompressionProviderFactory.Default,
                    TestId = "InvalidAlgorithm",
                    ExpectedException = new ExpectedException(typeof(SecurityTokenDecompressionFailedException), "IDX10679:", typeof(NotSupportedException))
                },
                new JWEDecompressionTheoryData
                {
                    ValidationParameters = Default.JWECompressionTokenValidationParameters,
                    JWECompressionString = ReferenceTokens.JWEInvalidCompressionTokenWithDEF,
                    CompressionProviderFactory = CompressionProviderFactory.Default,
                    TestId = "InvalidToken",
                    ExpectedException = new ExpectedException(typeof(SecurityTokenDecompressionFailedException), "IDX10679:", typeof(InvalidDataException))
                },
                new JWEDecompressionTheoryData
                {
                    ValidationParameters = Default.JWECompressionTokenValidationParameters,
                    JWECompressionString = ReferenceTokens.JWECompressionTokenWithDEF,
                    CompressionProviderFactory = null,
                    TestId = "NullCompressionProviderFactory",
                    ExpectedException = ExpectedException.ArgumentNullException("IDX10000:")
                },
                new JWEDecompressionTheoryData
                {
                    ValidationParameters = Default.JWECompressionTokenValidationParameters,
                    CompressionProviderFactory = compressionProviderFactoryForCustom,
                    JWECompressionString = ReferenceTokens.JWECompressionTokenWithCustomAlgorithm,
                    TestId = "CustomCompressionProviderSucceeds"
                },
                new JWEDecompressionTheoryData
                {
                    ValidationParameters = Default.JWECompressionTokenValidationParameters,
                    JWECompressionString = ReferenceTokens.JWEInvalidCompressionTokenWithDEF,
                    CompressionProviderFactory = compressionProviderFactoryForCustom2,
                    TestId = "CustomCompressionProviderFails",
                    ExpectedException = new ExpectedException(typeof(SecurityTokenDecompressionFailedException), "IDX10679:", typeof(InvalidOperationException))
                }
            });
        }
        public void EncodedStringConstruction()
        {
            Console.WriteLine("Entering: JwtSecurityToken_EncodedStringConstruction");
            string[] tokenParts = EncodedJwts.Asymmetric_LocalSts.Split('.');

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: OverClaims",
                EncodedString     = EncodedJwts.OverClaims,
                ExpectedException = ExpectedException.NoExceptionExpected,
            });


            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: InvalidPayloadFormat",
                EncodedString     = EncodedJwts.InvalidPayload,
                ExpectedException = ExpectedException.ArgumentException(substringExpected: "IDX10703:", inner: typeof(FormatException)),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: null",
                EncodedString     = null,
                ExpectedException = ExpectedException.ArgumentNullException(),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: string.Empty",
                EncodedString     = string.Empty,
                ExpectedException = ExpectedException.ArgumentNullException(),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: single character: '1'",
                EncodedString     = "1",
                ExpectedException = ExpectedException.ArgumentException(substringExpected: "IDX10709:"),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: two parts each a single character: '1.2'",
                EncodedString     = "1.2",
                ExpectedException = ExpectedException.ArgumentException(substringExpected: "IDX10709:"),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: header is not encoded properly: '123'",
                EncodedString     = string.Format("{0}.{1}.{2}", "123", tokenParts[1], tokenParts[2]),
                ExpectedException = ExpectedException.ArgumentException(substringExpected: "IDX10703:", inner: typeof(Newtonsoft.Json.JsonReaderException)),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: header is not encoded properly: '123=='",
                EncodedString     = string.Format("{0}.{1}.{2}", "123==", tokenParts[1], tokenParts[2]),
                ExpectedException = ExpectedException.ArgumentException(substringExpected: "IDX10709"),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: payload is not encoded correctly: '123'",
                EncodedString     = string.Format("{1}.{0}.{2}", "123", tokenParts[0], tokenParts[2]),
                ExpectedException = ExpectedException.ArgumentException(substringExpected: "IDX10703:", inner: typeof(Newtonsoft.Json.JsonReaderException)),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: payload is not encoded properly: '123=='",
                EncodedString     = string.Format("{1}.{0}.{2}", "123==", tokenParts[0], tokenParts[2]),
                ExpectedException = ExpectedException.ArgumentException(substringExpected: "IDX10709:"),
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: valid encoding, NO signature (JWT_AsymmetricSigned_AcsV2)",
                EncodedString     = string.Format("{0}.{1}.", tokenParts[0], tokenParts[1]),
                ExpectedException = ExpectedException.NoExceptionExpected,
            });

            RunEncodedTest(new JwtSecurityTokenTestVariation
            {
                Name              = "EncodedString: invalid encoding, 4 parts",
                EncodedString     = string.Format("{0}.{1}.{2}.{3}", tokenParts[0], tokenParts[1], tokenParts[2], tokenParts[2]),
                ExpectedException = ExpectedException.ArgumentException(substringExpected: "IDX10709:"),
            });
        }