Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cherry-pick Cache context switches (#2724) #2775

Open
wants to merge 9 commits into
base: dev6x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
using Microsoft.IdentityModel.Json.Linq;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens.Json;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
using System.Security.Claims;
westin-m marked this conversation as resolved.
Show resolved Hide resolved

#if !NET45
using System.IO;
Expand Down Expand Up @@ -537,8 +539,21 @@ internal static JsonDocument GetJsonDocumentFromBase64UrlEncodedString(string ra
{
return Base64UrlEncoding.Decode<JsonDocument>(rawString, startIndex, length, ParseDocument);
}
#endif
internal static string GetStringClaimValueType(string str, string claimType)
westin-m marked this conversation as resolved.
Show resolved Hide resolved
{
if (!string.IsNullOrEmpty(claimType) && !AppContextSwitches.TryAllStringClaimsAsDateTime && JsonSerializerPrimitives.IsKnownToNotBeDateTime(claimType))
return ClaimValueTypes.String;

if (DateTime.TryParse(str, out DateTime dateTimeValue))
{
string dtUniversal = dateTimeValue.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture);
if (dtUniversal.Equals(str, StringComparison.Ordinal))
return ClaimValueTypes.DateTime;
}

return ClaimValueTypes.String;
}
#endif
}
}

67 changes: 63 additions & 4 deletions src/Microsoft.IdentityModel.Tokens/AppContextSwitches.cs
westin-m marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,73 @@ namespace Microsoft.IdentityModel.Tokens
/// </summary>
internal static class AppContextSwitches
{
#if NET461_OR_GREATER || NETCOREAPP || NETSTANDARD
/// <summary>
/// Enables a new behavior of using <see cref="CaseSensitiveClaimsIdentity"/> instead of <see cref="ClaimsIdentity"/> globally.
/// Enables a fallback to the previous behavior of using <see cref="ClaimsIdentity"/> instead of <see cref="CaseSensitiveClaimsIdentity"/> globally.
westin-m marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
internal const string UseCaseSensitiveClaimsIdentityTypeSwitch = "Microsoft.IdentityModel.Tokens.UseCaseSensitiveClaimsIdentityType";
internal const string UseClaimsIdentityTypeSwitch = "Microsoft.IdentityModel.Tokens.UseClaimsIdentityType";

#if NET46_OR_GREATER || NETCOREAPP || NETSTANDARD
internal static bool UseCaseSensitiveClaimsIdentityType() => AppContext.TryGetSwitch(UseCaseSensitiveClaimsIdentityTypeSwitch, out bool useCaseSensitiveClaimsIdentityType) && useCaseSensitiveClaimsIdentityType;
private static bool? _useClaimsIdentityType;

internal static bool UseClaimsIdentityType => _useClaimsIdentityType ??= (AppContext.TryGetSwitch(UseClaimsIdentityTypeSwitch, out bool useClaimsIdentityType) && useClaimsIdentityType);

/// <summary>
/// When validating the issuer signing key, specifies whether to fail if the 'tid' claim is missing.
/// </summary>
internal const string DoNotFailOnMissingTidSwitch = "Switch.Microsoft.IdentityModel.DontFailOnMissingTidValidateIssuerSigning";

private static bool? _doNotFailOnMissingTid;

internal static bool DoNotFailOnMissingTid => _doNotFailOnMissingTid ??= (AppContext.TryGetSwitch(DoNotFailOnMissingTidSwitch, out bool doNotFailOnMissingTid) && doNotFailOnMissingTid);

/// <summary>
/// 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.
/// </summary>
internal const string TryAllStringClaimsAsDateTimeSwitch = "Switch.Microsoft.IdentityModel.TryAllStringClaimsAsDateTime";
keegan-caruso marked this conversation as resolved.
Show resolved Hide resolved

private static bool? _tryAllStringClaimsAsDateTime;

internal static bool TryAllStringClaimsAsDateTime => _tryAllStringClaimsAsDateTime ??= (AppContext.TryGetSwitch(TryAllStringClaimsAsDateTimeSwitch, out bool tryAsDateTime) && tryAsDateTime);

/// <summary>
/// Controls whether to validate the length of the authentication tag when decrypting a token.
/// </summary>
internal const string SkipValidationOfAuthenticationTagLengthSwitch = "Switch.Microsoft.IdentityModel.SkipAuthenticationTagLengthValidation";

private static bool? _skipValidationOfAuthenticationTagLength;

internal static bool ShouldValidateAuthenticationTagLength => _skipValidationOfAuthenticationTagLength ??= !(AppContext.TryGetSwitch(SkipValidationOfAuthenticationTagLengthSwitch, out bool skipValidation) && skipValidation);

/// <summary>
/// Controls whether to use the short name for the RSA OAEP key wrap algorithm.
/// </summary>
internal const string UseShortNameForRsaOaepKeySwitch = "Switch.Microsoft.IdentityModel.UseShortNameForRsaOaepKey";

private static bool? _useShortNameForRsaOaepKey;

internal static bool ShouldUseShortNameForRsaOaepKey => _useShortNameForRsaOaepKey ??= AppContext.TryGetSwitch(UseShortNameForRsaOaepKeySwitch, out var useKeyWrap) && useKeyWrap;

/// <summary>
/// Used for testing to reset all switches to its default value.
/// </summary>
internal static void ResetAllSwitches()
{
_useClaimsIdentityType = null;
AppContext.SetSwitch(UseClaimsIdentityTypeSwitch, 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);
}
#else
// .NET 4.5 does not support AppContext switches. Always use ClaimsIdentity.
internal static bool UseCaseSensitiveClaimsIdentityType() => false;
Expand Down
37 changes: 22 additions & 15 deletions src/Microsoft.IdentityModel.Tokens/ClaimsIdentityFactory.cs
westin-m marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,43 @@

namespace Microsoft.IdentityModel.Tokens
{
#if !NET45
/// <summary>
/// Facilitates the creation of <see cref="ClaimsIdentity"/> and <see cref="CaseSensitiveClaimsIdentity"/> instances based on the <see cref="AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch"/>.
/// Facilitates the creation of <see cref="ClaimsIdentity"/> and <see cref="CaseSensitiveClaimsIdentity"/> instances based on the <see cref="AppContextSwitches.UseClaimsIdentityType"/>.
/// </summary>
#endif

internal static class ClaimsIdentityFactory
{
internal static ClaimsIdentity Create(IEnumerable<Claim> claims)
{
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType())
return new CaseSensitiveClaimsIdentity(claims);

return new ClaimsIdentity(claims);
#if !NET45
if (AppContextSwitches.UseClaimsIdentityType)
return new ClaimsIdentity(claims);
#endif
return new CaseSensitiveClaimsIdentity(claims);
}

internal static ClaimsIdentity Create(IEnumerable<Claim> claims, string authenticationType)
{
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType())
return new CaseSensitiveClaimsIdentity(claims, authenticationType);

return new ClaimsIdentity(claims, authenticationType);
#if !NET45
if (AppContextSwitches.UseClaimsIdentityType)
return new ClaimsIdentity(claims, authenticationType);
#endif
return new CaseSensitiveClaimsIdentity(claims, authenticationType);
}

internal static ClaimsIdentity Create(string authenticationType, string nameType, string roleType, SecurityToken securityToken)
{
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType())
return new CaseSensitiveClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType)
{
SecurityToken = securityToken,
};
#if !NET45

return new ClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType);
if (AppContextSwitches.UseClaimsIdentityType)
return new ClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType);
#endif
return new CaseSensitiveClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType)
{
SecurityToken = securityToken,
};
}
}
}
128 changes: 128 additions & 0 deletions src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Licensed to the .NET Foundation under one or more agreements.
westin-m marked this conversation as resolved.
Show resolved Hide resolved
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;

namespace Microsoft.IdentityModel.Tokens.Json
{
internal static class JsonSerializerPrimitives
{
#if !NET45
public static bool TryAllStringClaimsAsDateTime()
{
return AppContextSwitches.TryAllStringClaimsAsDateTime;
}
#endif

/// <summary>
/// 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
/// restricted claim names.
/// </summary>
private static readonly HashSet<string> s_knownNonDateTimeClaimTypes = new(StringComparer.Ordinal)
{
// Header Values.
"alg",
"cty",
"crit",
"enc",
"jku",
"jwk",
"kid",
"typ",
"x5c",
"x5t",
"x5t#S256",
"x5u",
"zip",
// JWT claims.
"acr",
"acrs",
"access_token",
"account_type",
"acct",
"actor",
"actort",
"actortoken",
"aio",
"altsecid",
"amr",
"app_displayname",
"appid",
"appidacr",
"at_hash",
"aud",
"authorization_code",
"azp",
"azpacr",
"c_hash",
"cnf",
"capolids",
"ctry",
"email",
"family_name",
"fwd",
"gender",
"given_name",
"groups",
"hasgroups",
"idp",
"idtyp",
"in_corp",
"ipaddr",
"iss",
"jti",
"login_hint",
"name",
"nameid",
"nickname",
"nonce",
"oid",
"onprem_sid",
"phone_number",
"phone_number_verified",
"pop_jwk",
"preferred_username",
"prn",
"puid",
"pwd_url",
"rh",
"role",
"roles",
"secaud",
"sid",
"sub",
"tenant_ctry",
"tenant_region_scope",
"tid",
"unique_name",
"upn",
"uti",
"ver",
"verified_primary_email",
"verified_secondary_email",
"vnet",
"website",
"wids",
"xms_cc",
"xms_edov",
"xms_pdl",
"xms_pl",
"xms_tpl",
"ztdid"
};

internal static bool IsKnownToNotBeDateTime(string claimType)
{
if (string.IsNullOrEmpty(claimType))
return true;

if (s_knownNonDateTimeClaimTypes.Contains(claimType))
return true;

return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ public static void EnableAadSigningKeyIssuerValidation(this TokenValidationParam
}

#if !NET45
internal const string DontFailOnMissingTidSwitch = "Switch.Microsoft.IdentityModel.DontFailOnMissingTidValidateIssuerSigning";
internal const string DoNotFailOnMissingTidSwitch = "Switch.Microsoft.IdentityModel.DontFailOnMissingTidValidateIssuerSigning";

private static bool DontFailOnMissingTid()
{
return (AppContext.TryGetSwitch(DontFailOnMissingTidSwitch, out bool dontFailOnMissingTid) && dontFailOnMissingTid);
return (AppContext.TryGetSwitch(DoNotFailOnMissingTidSwitch, out bool doNotFailOnMissingTid) && doNotFailOnMissingTid);
westin-m marked this conversation as resolved.
Show resolved Hide resolved
}
#endif

Expand Down Expand Up @@ -83,10 +83,9 @@ internal static bool ValidateIssuerSigningKey(SecurityKey securityKey, SecurityT
if (string.IsNullOrEmpty(tenantIdFromToken))
{
#if !NET45
if (DontFailOnMissingTid())
return true;
if (AppContextSwitches.DoNotFailOnMissingTid)
return true;
westin-m marked this conversation as resolved.
Show resolved Hide resolved
#endif

throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidIssuerException(LogMessages.IDX40009));
}

Expand Down
westin-m marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,9 @@ namespace Microsoft.IdentityModel.JsonWebTokens.Tests
public class JsonWebTokenHandlerClaimsIdentityTests
{

#if NET46_OR_GREATER || NETCOREAPP || NETSTANDARD
[Fact]
public void CreateClaimsIdentity_ReturnsCaseSensitveClaimsIdentity_WithAppContextSwitch()
{
AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, true);

var handler = new DerivedJsonWebTokenHandler();
var jsonWebToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor()));
var tokenValidationParameters = new TokenValidationParameters();
Expand All @@ -40,14 +37,17 @@ public void CreateClaimsIdentity_ReturnsCaseSensitveClaimsIdentity_WithAppContex
actualClaimsIdentity = handler.CreateClaimsIdentityInternal(jsonWebToken, tokenValidationParameters, Default.Issuer);
Assert.IsType<CaseSensitiveClaimsIdentity>(actualClaimsIdentity);
Assert.NotNull(((CaseSensitiveClaimsIdentity)actualClaimsIdentity).SecurityToken);

AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, false);
}
#if !NET452
AppContextSwitches.ResetAllSwitches();
#endif
}

#if NET46_OR_GREATER || NETCOREAPP || NETSTANDARD
[Fact]
public void CreateClaimsIdentity_ReturnsClaimsIdentity_ByDefault()
{
AppContext.SetSwitch(AppContextSwitches.UseClaimsIdentityTypeSwitch, true);

var handler = new DerivedJsonWebTokenHandler();
var jsonWebToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor()));
var tokenValidationParameters = new TokenValidationParameters();
Expand All @@ -58,7 +58,10 @@ public void CreateClaimsIdentity_ReturnsClaimsIdentity_ByDefault()
// This will also test mapped claims flow.
handler.MapInboundClaims = true;
Assert.IsType<ClaimsIdentity>(handler.CreateClaimsIdentityInternal(jsonWebToken, tokenValidationParameters, Default.Issuer));

AppContextSwitches.ResetAllSwitches();
}
#endif

private class DerivedJsonWebTokenHandler : JsonWebTokenHandler
{
Expand Down
Loading