From a75d614670670afe5e7b35128ad9a64a04727ef8 Mon Sep 17 00:00:00 2001 From: Peter <34331512+pmaytak@users.noreply.github.com> Date: Wed, 17 Jul 2024 13:04:32 -0700 Subject: [PATCH] Cherry pick Cache context switches (#2724) to 7x (#2726) * Cache context switches (#2724) * Cache context switches. * Refactor switch reset in tests. * Rename. * Refactor to reset switches in one method. * Fix tests. * Fix tests. * Add other context switches. * Fix. * Rename. * reset state in CreateClaimsIdentity_ReturnsClaimsIdentity_ByDefault --------- Co-authored-by: Keegan Caruso --- .../JwtTokenUtilities.cs | 2 +- .../AppContextSwitches.cs | 62 ++++++++++++++++++- .../ClaimsIdentityFactory.cs | 6 +- .../AuthenticatedEncryptionProvider.cs | 8 +-- .../Json/JsonSerializerPrimitives.cs | 11 +--- .../X509EncryptingCredentials.cs | 9 +-- .../AadTokenValidationParametersExtension.cs | 9 +-- .../JsonWebTokenHandlerClaimsIdentityTests.cs | 4 +- .../JsonWebTokenHandlerTests.cs | 41 +++++++----- .../ClaimsIdentityFactoryTests.cs | 2 +- .../AadSigningKeyIssuerValidatorTests.cs | 19 ++---- ...tyTokenHandlerTests.WithContextSwitches.cs | 8 +-- 12 files changed, 108 insertions(+), 73 deletions(-) diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs index 52b84a7b37..c83e5fddad 100644 --- a/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs +++ b/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs @@ -609,7 +609,7 @@ internal static string GetStringClaimValueType(string str) internal static string GetStringClaimValueType(string str, string claimType) { - if (!string.IsNullOrEmpty(claimType) && !JsonSerializerPrimitives.TryAllStringClaimsAsDateTime() && JsonSerializerPrimitives.IsKnownToNotBeDateTime(claimType)) + if (!string.IsNullOrEmpty(claimType) && !AppContextSwitches.TryAllStringClaimsAsDateTime && JsonSerializerPrimitives.IsKnownToNotBeDateTime(claimType)) return ClaimValueTypes.String; if (DateTime.TryParse(str, out DateTime dateTimeValue)) diff --git a/src/Microsoft.IdentityModel.Tokens/AppContextSwitches.cs b/src/Microsoft.IdentityModel.Tokens/AppContextSwitches.cs index 865e7d0de0..afbd82f7c8 100644 --- a/src/Microsoft.IdentityModel.Tokens/AppContextSwitches.cs +++ b/src/Microsoft.IdentityModel.Tokens/AppContextSwitches.cs @@ -16,6 +16,66 @@ internal static class AppContextSwitches /// internal const string UseCaseSensitiveClaimsIdentityTypeSwitch = "Microsoft.IdentityModel.Tokens.UseCaseSensitiveClaimsIdentity"; - internal static bool UseCaseSensitiveClaimsIdentityType() => (AppContext.TryGetSwitch(UseCaseSensitiveClaimsIdentityTypeSwitch, out bool useCaseSensitiveClaimsIdentityType) && useCaseSensitiveClaimsIdentityType); + private static bool? _useCaseSensitiveClaimsIdentityType; + + internal static bool UseCaseSensitiveClaimsIdentityType => _useCaseSensitiveClaimsIdentityType ??= (AppContext.TryGetSwitch(UseCaseSensitiveClaimsIdentityTypeSwitch, out bool useCaseSensitiveClaimsIdentityType) && useCaseSensitiveClaimsIdentityType); + + /// + /// When validating the issuer signing key, specifies whether to fail if the 'tid' claim is missing. + /// + internal const string DoNotFailOnMissingTidSwitch = "Switch.Microsoft.IdentityModel.DontFailOnMissingTidValidateIssuerSigning"; + + private static bool? _doNotFailOnMissingTid; + + internal static bool DoNotFailOnMissingTid => _doNotFailOnMissingTid ??= (AppContext.TryGetSwitch(DoNotFailOnMissingTidSwitch, out bool doNotFailOnMissingTid) && doNotFailOnMissingTid); + + /// + /// When reading claims from the token, specifies whether to try to convert all string claims to DateTime. + /// Some claims are known not to be DateTime, so conversion is skipped. + /// + internal const string TryAllStringClaimsAsDateTimeSwitch = "Switch.Microsoft.IdentityModel.TryAllStringClaimsAsDateTime"; + + private static bool? _tryAllStringClaimsAsDateTime; + + internal static bool TryAllStringClaimsAsDateTime => _tryAllStringClaimsAsDateTime ??= (AppContext.TryGetSwitch(TryAllStringClaimsAsDateTimeSwitch, out bool tryAsDateTime) && tryAsDateTime); + + /// + /// Controls whether to validate the length of the authentication tag when decrypting a token. + /// + internal const string SkipValidationOfAuthenticationTagLengthSwitch = "Switch.Microsoft.IdentityModel.SkipAuthenticationTagLengthValidation"; + + private static bool? _skipValidationOfAuthenticationTagLength; + + internal static bool ShouldValidateAuthenticationTagLength => _skipValidationOfAuthenticationTagLength ??= !(AppContext.TryGetSwitch(SkipValidationOfAuthenticationTagLengthSwitch, out bool skipValidation) && skipValidation); + + /// + /// Controls whether to use the short name for the RSA OAEP key wrap algorithm. + /// + internal const string UseShortNameForRsaOaepKeySwitch = "Switch.Microsoft.IdentityModel.UseShortNameForRsaOaepKey"; + + private static bool? _useShortNameForRsaOaepKey; + + internal static bool ShouldUseShortNameForRsaOaepKey => _useShortNameForRsaOaepKey ??= AppContext.TryGetSwitch(UseShortNameForRsaOaepKeySwitch, out var useKeyWrap) && useKeyWrap; + + /// + /// Used for testing to reset all switches to its default value. + /// + internal static void ResetAllSwitches() + { + _useCaseSensitiveClaimsIdentityType = null; + AppContext.SetSwitch(UseCaseSensitiveClaimsIdentityTypeSwitch, false); + + _doNotFailOnMissingTid = null; + AppContext.SetSwitch(DoNotFailOnMissingTidSwitch, false); + + _tryAllStringClaimsAsDateTime = null; + AppContext.SetSwitch(TryAllStringClaimsAsDateTimeSwitch, false); + + _skipValidationOfAuthenticationTagLength = null; + AppContext.SetSwitch(SkipValidationOfAuthenticationTagLengthSwitch, false); + + _useShortNameForRsaOaepKey = null; + AppContext.SetSwitch(UseShortNameForRsaOaepKeySwitch, false); + } } } diff --git a/src/Microsoft.IdentityModel.Tokens/ClaimsIdentityFactory.cs b/src/Microsoft.IdentityModel.Tokens/ClaimsIdentityFactory.cs index 1f6f56bc74..6fa1781aef 100644 --- a/src/Microsoft.IdentityModel.Tokens/ClaimsIdentityFactory.cs +++ b/src/Microsoft.IdentityModel.Tokens/ClaimsIdentityFactory.cs @@ -13,7 +13,7 @@ internal static class ClaimsIdentityFactory { internal static ClaimsIdentity Create(IEnumerable claims) { - if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType()) + if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType) return new CaseSensitiveClaimsIdentity(claims); return new ClaimsIdentity(claims); @@ -21,7 +21,7 @@ internal static ClaimsIdentity Create(IEnumerable claims) internal static ClaimsIdentity Create(IEnumerable claims, string authenticationType) { - if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType()) + if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType) return new CaseSensitiveClaimsIdentity(claims, authenticationType); return new ClaimsIdentity(claims, authenticationType); @@ -29,7 +29,7 @@ internal static ClaimsIdentity Create(IEnumerable claims, string authenti internal static ClaimsIdentity Create(string authenticationType, string nameType, string roleType, SecurityToken securityToken) { - if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType()) + if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType) return new CaseSensitiveClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType) { SecurityToken = securityToken, diff --git a/src/Microsoft.IdentityModel.Tokens/Encryption/AuthenticatedEncryptionProvider.cs b/src/Microsoft.IdentityModel.Tokens/Encryption/AuthenticatedEncryptionProvider.cs index b6b063936d..f8337cf488 100644 --- a/src/Microsoft.IdentityModel.Tokens/Encryption/AuthenticatedEncryptionProvider.cs +++ b/src/Microsoft.IdentityModel.Tokens/Encryption/AuthenticatedEncryptionProvider.cs @@ -33,7 +33,6 @@ private struct AuthenticatedKeys private DecryptionDelegate DecryptFunction; private EncryptionDelegate EncryptFunction; private const string _className = "Microsoft.IdentityModel.Tokens.AuthenticatedEncryptionProvider"; - internal const string _skipValidationOfAuthenticationTagLength = "Switch.Microsoft.IdentityModel.SkipAuthenticationTagLengthValidation"; /// /// Initializes a new instance of the class used for encryption and decryption. @@ -167,7 +166,7 @@ private AuthenticatedEncryptionResult EncryptWithAesCbc(byte[] plaintext, byte[] private byte[] DecryptWithAesCbc(byte[] ciphertext, byte[] authenticatedData, byte[] iv, byte[] authenticationTag) { // Verify authentication Tag - if (ShouldValidateAuthenticationTagLength() + if (AppContextSwitches.ShouldValidateAuthenticationTagLength && SymmetricSignatureProvider.ExpectedSignatureSizeInBytes.TryGetValue(Algorithm, out int expectedTagLength) && expectedTagLength != authenticationTag.Length) throw LogHelper.LogExceptionMessage(new SecurityTokenDecryptionFailedException( @@ -197,11 +196,6 @@ private byte[] DecryptWithAesCbc(byte[] ciphertext, byte[] authenticatedData, by } } - private static bool ShouldValidateAuthenticationTagLength() - { - return !(AppContext.TryGetSwitch(_skipValidationOfAuthenticationTagLength, out bool skipValidation) && skipValidation); - } - private AuthenticatedKeys CreateAuthenticatedKeys() { ValidateKeySize(Key, Algorithm); diff --git a/src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs b/src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs index f539555a8b..c4f735e0cd 100644 --- a/src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs +++ b/src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs @@ -146,7 +146,7 @@ internal static object CreateObjectFromJsonElement(JsonElement jsonElement, int if (jsonElement.ValueKind == JsonValueKind.String) { - if (!string.IsNullOrEmpty(claimType) && !TryAllStringClaimsAsDateTime() && IsKnownToNotBeDateTime(claimType)) + if (!string.IsNullOrEmpty(claimType) && !AppContextSwitches.TryAllStringClaimsAsDateTime && IsKnownToNotBeDateTime(claimType)) return jsonElement.GetString(); if (DateTime.TryParse(jsonElement.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime dateTime)) @@ -706,13 +706,6 @@ internal static string ReadStringOrNumberAsString(ref Utf8JsonReader reader, str return retVal; } - internal const string TryToCreateDateTimeClaimsSwitch = "Switch.Microsoft.IdentityModel.TryAllStringClaimsAsDateTime"; - - public static bool TryAllStringClaimsAsDateTime() - { - return (AppContext.TryGetSwitch(TryToCreateDateTimeClaimsSwitch, out bool tryAsDateTime) && tryAsDateTime); - } - /// /// This is a non-exhaustive list of claim types that are not expected to be DateTime values /// sourced from expected Entra V1 and V2 claims, OpenID Connect claims, and a selection of @@ -834,7 +827,7 @@ internal static object ReadStringAsObject(ref Utf8JsonReader reader, string prop string originalString = reader.GetString(); - if (!TryAllStringClaimsAsDateTime() && IsKnownToNotBeDateTime(propertyName)) + if (!AppContextSwitches.TryAllStringClaimsAsDateTime && IsKnownToNotBeDateTime(propertyName)) { reader.Read(); return originalString; diff --git a/src/Microsoft.IdentityModel.Tokens/X509EncryptingCredentials.cs b/src/Microsoft.IdentityModel.Tokens/X509EncryptingCredentials.cs index ec0f483dd8..0b211261e7 100644 --- a/src/Microsoft.IdentityModel.Tokens/X509EncryptingCredentials.cs +++ b/src/Microsoft.IdentityModel.Tokens/X509EncryptingCredentials.cs @@ -11,8 +11,6 @@ namespace Microsoft.IdentityModel.Tokens /// public class X509EncryptingCredentials : EncryptingCredentials { - internal const string _useShortNameForRsaOaepKey = "Switch.Microsoft.IdentityModel.UseShortNameForRsaOaepKey"; - /// /// Designed to construct based on a x509 certificate. /// @@ -53,12 +51,7 @@ public X509Certificate2 Certificate private static string GetEncryptionAlgorithm() { - return ShouldUseShortNameForRsaOaepKey() ? SecurityAlgorithms.RsaOAEP : SecurityAlgorithms.DefaultAsymmetricKeyWrapAlgorithm; - } - - private static bool ShouldUseShortNameForRsaOaepKey() - { - return AppContext.TryGetSwitch(_useShortNameForRsaOaepKey, out var useKeyWrap) && useKeyWrap; + return AppContextSwitches.ShouldUseShortNameForRsaOaepKey ? SecurityAlgorithms.RsaOAEP : SecurityAlgorithms.DefaultAsymmetricKeyWrapAlgorithm; } } } diff --git a/src/Microsoft.IdentityModel.Validators/AadTokenValidationParametersExtension.cs b/src/Microsoft.IdentityModel.Validators/AadTokenValidationParametersExtension.cs index dd5f011484..47e7fb3ada 100644 --- a/src/Microsoft.IdentityModel.Validators/AadTokenValidationParametersExtension.cs +++ b/src/Microsoft.IdentityModel.Validators/AadTokenValidationParametersExtension.cs @@ -45,13 +45,6 @@ public static void EnableAadSigningKeyIssuerValidation(this TokenValidationParam }; } - internal const string DontFailOnMissingTidSwitch = "Switch.Microsoft.IdentityModel.DontFailOnMissingTidValidateIssuerSigning"; - - private static bool DontFailOnMissingTid() - { - return (AppContext.TryGetSwitch(DontFailOnMissingTidSwitch, out bool dontFailOnMissingTid) && dontFailOnMissingTid); - } - /// /// Validates the issuer signing key. /// @@ -81,7 +74,7 @@ internal static bool ValidateIssuerSigningKey(SecurityKey securityKey, SecurityT var tenantIdFromToken = GetTid(securityToken); if (string.IsNullOrEmpty(tenantIdFromToken)) { - if (DontFailOnMissingTid()) + if (AppContextSwitches.DoNotFailOnMissingTid) return true; throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidIssuerException(LogMessages.IDX40009)); diff --git a/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandlerClaimsIdentityTests.cs b/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandlerClaimsIdentityTests.cs index e91c6a27b1..bd0b064156 100644 --- a/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandlerClaimsIdentityTests.cs +++ b/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandlerClaimsIdentityTests.cs @@ -32,6 +32,8 @@ public void CreateClaimsIdentity_ReturnsClaimsIdentity_ByDefault() handler.MapInboundClaims = true; actualClaimsIdentity = handler.CreateClaimsIdentityInternal(jsonWebToken, tokenValidationParameters, Default.Issuer); Assert.IsType(actualClaimsIdentity); + + AppContextSwitches.ResetAllSwitches(); } [Fact] @@ -61,7 +63,7 @@ public void CreateClaimsIdentity_ReturnsCaseSensitiveClaimsIdentity_WithAppConte Assert.IsType(actualClaimsIdentity); Assert.NotNull(((CaseSensitiveClaimsIdentity)actualClaimsIdentity).SecurityToken); - AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, false); + AppContextSwitches.ResetAllSwitches(); } private class DerivedJsonWebTokenHandler : JsonWebTokenHandler diff --git a/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandlerTests.cs b/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandlerTests.cs index 210a2ebcc1..a73452fc19 100644 --- a/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandlerTests.cs +++ b/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandlerTests.cs @@ -4192,9 +4192,11 @@ public static TheoryData IncludeSecurityTokenOnFailureTes [Theory, MemberData(nameof(ValidateAuthenticationTagLengthTheoryData))] public void ValidateTokenAsync_ModifiedAuthNTag(CreateTokenTheoryData theoryData) { - // arrange - AppContext.SetSwitch(AuthenticatedEncryptionProvider._skipValidationOfAuthenticationTagLength, theoryData.EnableAppContextSwitch); - var payload = new JObject() + try + { + // arrange + AppContext.SetSwitch(AppContextSwitches.SkipValidationOfAuthenticationTagLengthSwitch, theoryData.EnableAppContextSwitch); + var payload = new JObject() { { JwtRegisteredClaimNames.Email, "Bob@contoso.com" }, { JwtRegisteredClaimNames.GivenName, "Bob" }, @@ -4205,24 +4207,29 @@ public void ValidateTokenAsync_ModifiedAuthNTag(CreateTokenTheoryData theoryData { JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(DateTime.Now.AddDays(1)).ToString() }, }.ToString(); - var jsonWebTokenHandler = new JsonWebTokenHandler(); - var signingCredentials = Default.SymmetricSigningCredentials; + var jsonWebTokenHandler = new JsonWebTokenHandler(); + var signingCredentials = Default.SymmetricSigningCredentials; - if (SupportedAlgorithms.IsAesGcm(theoryData.Algorithm)) - { - theoryData.EncryptingCredentials.CryptoProviderFactory = new CryptoProviderFactoryForGcm(); - } + if (SupportedAlgorithms.IsAesGcm(theoryData.Algorithm)) + { + theoryData.EncryptingCredentials.CryptoProviderFactory = new CryptoProviderFactoryForGcm(); + } - var jwe = jsonWebTokenHandler.CreateToken(payload, signingCredentials, theoryData.EncryptingCredentials); - var jweWithExtraCharacters = jwe + "_cannoli_hunts_truffles_"; + var jwe = jsonWebTokenHandler.CreateToken(payload, signingCredentials, theoryData.EncryptingCredentials); + var jweWithExtraCharacters = jwe + "_cannoli_hunts_truffles_"; - // act - // calling ValidateTokenAsync.Result to prevent tests from sharing app context switch property - // normally, we would want to await ValidateTokenAsync().ConfigureAwait(false) - var tokenValidationResult = jsonWebTokenHandler.ValidateTokenAsync(jweWithExtraCharacters, theoryData.ValidationParameters).Result; + // act + // calling ValidateTokenAsync.Result to prevent tests from sharing app context switch property + // normally, we would want to await ValidateTokenAsync().ConfigureAwait(false) + var tokenValidationResult = jsonWebTokenHandler.ValidateTokenAsync(jweWithExtraCharacters, theoryData.ValidationParameters).Result; - // assert - Assert.Equal(theoryData.IsValid, tokenValidationResult.IsValid); + // assert + Assert.Equal(theoryData.IsValid, tokenValidationResult.IsValid); + } + finally + { + AppContextSwitches.ResetAllSwitches(); + } } public static TheoryData ValidateAuthenticationTagLengthTheoryData() diff --git a/test/Microsoft.IdentityModel.Tokens.Tests/ClaimsIdentityFactoryTests.cs b/test/Microsoft.IdentityModel.Tokens.Tests/ClaimsIdentityFactoryTests.cs index c0e6e9b0d1..357493d019 100644 --- a/test/Microsoft.IdentityModel.Tokens.Tests/ClaimsIdentityFactoryTests.cs +++ b/test/Microsoft.IdentityModel.Tokens.Tests/ClaimsIdentityFactoryTests.cs @@ -42,7 +42,7 @@ public void Create_FromTokenValidationParameters_ReturnsCorrectClaimsIdentity(bo Assert.IsType(actualClaimsIdentity); } - AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, false); + AppContextSwitches.ResetAllSwitches(); } [Theory] diff --git a/test/Microsoft.IdentityModel.Validators.Tests/AadSigningKeyIssuerValidatorTests.cs b/test/Microsoft.IdentityModel.Validators.Tests/AadSigningKeyIssuerValidatorTests.cs index a0a70fddf8..4745518833 100644 --- a/test/Microsoft.IdentityModel.Validators.Tests/AadSigningKeyIssuerValidatorTests.cs +++ b/test/Microsoft.IdentityModel.Validators.Tests/AadSigningKeyIssuerValidatorTests.cs @@ -181,7 +181,7 @@ public void ValidateIssuerSigningKeyTests(AadSigningKeyIssuerTheoryData theoryDa } finally { - theoryData.TearDownAction?.Invoke(); + AppContextSwitches.ResetAllSwitches(); } TestUtilities.AssertFailIfErrors(context); @@ -345,8 +345,7 @@ public static TheoryData ValidateIssuerSigningKey SecurityKey = KeyingMaterial.JsonWebKeyP256, SecurityToken = new JwtSecurityToken(), OpenIdConnectConfiguration = mockConfiguration, - SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, true), - TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false) + SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, true), }); theoryData.Add(new AadSigningKeyIssuerTheoryData @@ -356,8 +355,7 @@ public static TheoryData ValidateIssuerSigningKey SecurityToken = new JwtSecurityToken(), OpenIdConnectConfiguration = mockConfiguration, ExpectedException = ExpectedException.SecurityTokenInvalidIssuerException("IDX40009"), - SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false), - TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, isEnabled: false) + SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, false), }); theoryData.Add(new AadSigningKeyIssuerTheoryData @@ -366,8 +364,7 @@ public static TheoryData ValidateIssuerSigningKey SecurityKey = KeyingMaterial.JsonWebKeyP256, SecurityToken = new JwtSecurityToken(), OpenIdConnectConfiguration = mockConfiguration, - SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, true), - TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false) + SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, true), }); theoryData.Add(new AadSigningKeyIssuerTheoryData @@ -377,8 +374,7 @@ public static TheoryData ValidateIssuerSigningKey SecurityToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor(Default.SymmetricSigningCredentials, [issClaim]))), OpenIdConnectConfiguration = mockConfiguration, ExpectedException = ExpectedException.SecurityTokenInvalidIssuerException("IDX40009"), - SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false), - TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, isEnabled: false) + SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, false), }); theoryData.Add(new AadSigningKeyIssuerTheoryData @@ -387,8 +383,7 @@ public static TheoryData ValidateIssuerSigningKey SecurityKey = KeyingMaterial.JsonWebKeyP256, SecurityToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor(Default.SymmetricSigningCredentials, [issClaim]))), OpenIdConnectConfiguration = mockConfiguration, - SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, true), - TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false) + SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, true), }); theoryData.Add(new AadSigningKeyIssuerTheoryData @@ -454,8 +449,6 @@ public class AadSigningKeyIssuerTheoryData : TheoryDataBase public bool SetDelegateWithoutConfig { get; set; } = false; public Action SetupAction { get; set; } - - public Action TearDownAction { get; set; } } } } diff --git a/test/System.IdentityModel.Tokens.Jwt.Tests/JwtSecurityTokenHandlerTests.WithContextSwitches.cs b/test/System.IdentityModel.Tokens.Jwt.Tests/JwtSecurityTokenHandlerTests.WithContextSwitches.cs index 7e87575e11..e5bc44a69e 100644 --- a/test/System.IdentityModel.Tokens.Jwt.Tests/JwtSecurityTokenHandlerTests.WithContextSwitches.cs +++ b/test/System.IdentityModel.Tokens.Jwt.Tests/JwtSecurityTokenHandlerTests.WithContextSwitches.cs @@ -16,7 +16,7 @@ public class JwtSecurityTokenHandlerTestsWithContextSwitches [InlineData(SecurityAlgorithms.RsaOaepKeyWrap, false)] public void JwtSecurityTokenHandler_CreateToken_AddShortFormMappingForRsaOAEP(string algorithm, bool useShortNameForRsaOaepKey) { - AppContext.SetSwitch(X509EncryptingCredentials._useShortNameForRsaOaepKey, useShortNameForRsaOaepKey); + AppContext.SetSwitch(AppContextSwitches.UseShortNameForRsaOaepKeySwitch, useShortNameForRsaOaepKey); var encryptingCredentials = new X509EncryptingCredentials(Default.Certificate); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); @@ -24,7 +24,7 @@ public void JwtSecurityTokenHandler_CreateToken_AddShortFormMappingForRsaOAEP(st Assert.Equal(token.Header.Alg, algorithm); - AppContext.SetSwitch(X509EncryptingCredentials._useShortNameForRsaOaepKey, false); + AppContextSwitches.ResetAllSwitches(); } [Theory] @@ -32,7 +32,7 @@ public void JwtSecurityTokenHandler_CreateToken_AddShortFormMappingForRsaOAEP(st [InlineData(SecurityAlgorithms.RsaOaepKeyWrap, false)] public void JsonWebTokenHandler_CreateToken_AddShortFormMappingForRsaOAEP(string algorithm, bool useShortNameForRsaOaepKey) { - AppContext.SetSwitch(X509EncryptingCredentials._useShortNameForRsaOaepKey, useShortNameForRsaOaepKey); + AppContext.SetSwitch(AppContextSwitches.UseShortNameForRsaOaepKeySwitch, useShortNameForRsaOaepKey); var encryptingCredentials = new X509EncryptingCredentials(Default.Certificate); JsonWebTokenHandler tokenHandler = new JsonWebTokenHandler(); @@ -40,7 +40,7 @@ public void JsonWebTokenHandler_CreateToken_AddShortFormMappingForRsaOAEP(string Assert.Equal(jsonToken.Alg, algorithm); - AppContext.SetSwitch(X509EncryptingCredentials._useShortNameForRsaOaepKey, false); + AppContextSwitches.ResetAllSwitches(); } private JwtSecurityToken CreateJwtSecurityToken(JwtSecurityTokenHandler tokenHandler, X509EncryptingCredentials encryptingCredentials)