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

Add CaseSensitiveClaimsIdentity type. #2700

Merged
merged 24 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
891f671
Add CaseSensitiveClaimsIdentity. Update JsonWebTokenHandler.
pmaytak Jul 11, 2024
63bfa21
Move switch to a separate class. Update claims identity creation code.
pmaytak Jul 11, 2024
b8b2fbc
Add test.
pmaytak Jul 11, 2024
98fc5f4
Update AppContextSwitches
pmaytak Jul 11, 2024
f15f4c4
Update test/Microsoft.IdentityModel.Tokens.Tests/CaseSensitiveClaimsI…
pmaytak Jul 12, 2024
a76cc11
Update comments.
pmaytak Jul 12, 2024
c0aa6bf
Merge remote-tracking branch 'origin/dev' into pmaytak/cs-claims
pmaytak Jul 12, 2024
b18236d
Update ClaimsIdentity code creation in src.
pmaytak Jul 12, 2024
dd1566e
Add tests.
pmaytak Jul 12, 2024
42eb9a0
Update tests to use correct types.
pmaytak Jul 12, 2024
c4bbcf6
Add SecurityToken property to CsClaimsIdentity.
pmaytak Jul 12, 2024
b19d572
Update tests to use CsClaimsIdentity.
pmaytak Jul 12, 2024
30b17fe
Refactor code into ClaimsIdentityFactory.
pmaytak Jul 12, 2024
2cfd756
Merge remote-tracking branch 'origin/dev' into pmaytak/cs-claims
pmaytak Jul 12, 2024
807790e
Update tests.
pmaytak Jul 13, 2024
73d4164
Update ClaimsIdentityFactory.
pmaytak Jul 13, 2024
25eed7f
Fix tests.
pmaytak Jul 13, 2024
c631785
Update tests for CaseSensitiveClaimsIdentity
Jul 13, 2024
bafae8b
ignore SecurityToken in IdentityComparer
Jul 13, 2024
36cdd6b
Set security token in ClaimsIdentityFactory. Add tests.
pmaytak Jul 15, 2024
0f93969
Apply suggestions from code review
pmaytak Jul 15, 2024
9532084
Update test.
pmaytak Jul 15, 2024
aef682c
Merge branch 'pmaytak/cs-claims' of https://github.com/AzureAD/azure-…
pmaytak Jul 15, 2024
11faf0b
Merge remote-tracking branch 'origin/dev' into pmaytak/cs-claims
pmaytak Jul 15, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ private ClaimsIdentity CreateClaimsIdentityWithMapping(JsonWebToken jwtToken, To
{
_ = validationParameters ?? throw LogHelper.LogArgumentNullException(nameof(validationParameters));

ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(jwtToken, issuer);
ClaimsIdentity identity = CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(jwtToken, validationParameters, issuer);
foreach (Claim jwtClaim in jwtToken.Claims)
{
bool wasMapped = _inboundClaimTypeMap.TryGetValue(jwtClaim.Type, out string claimType);
Expand Down Expand Up @@ -281,7 +281,7 @@ private ClaimsIdentity CreateClaimsIdentityPrivate(JsonWebToken jwtToken, TokenV
{
_ = validationParameters ?? throw LogHelper.LogArgumentNullException(nameof(validationParameters));

ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(jwtToken, issuer);
ClaimsIdentity identity = CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(jwtToken, validationParameters, issuer);
foreach (Claim jwtClaim in jwtToken.Claims)
{
string claimType = jwtClaim.Type;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,7 @@ protected virtual IEnumerable<ClaimsIdentity> ProcessStatements(SamlSecurityToke

if (!identityDict.TryGetValue(statement.Subject, out ClaimsIdentity identity))
{
identity = validationParameters.CreateClaimsIdentity(samlToken, issuer);
identity = CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(samlToken, validationParameters, issuer);
ProcessSubject(statement.Subject, identity, issuer);
identityDict.Add(statement.Subject, identity);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1314,7 +1314,8 @@ protected virtual ClaimsIdentity CreateClaimsIdentity(Saml2SecurityToken samlTok
actualIssuer = ClaimsIdentity.DefaultIssuer;
}

var identity = validationParameters.CreateClaimsIdentity(samlToken, actualIssuer);
var identity = CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(samlToken, validationParameters, issuer);

ProcessSubject(samlToken.Assertion.Subject, identity, actualIssuer);
ProcessStatements(samlToken.Assertion.Statements, identity, actualIssuer);

Expand Down
21 changes: 21 additions & 0 deletions src/Microsoft.IdentityModel.Tokens/AppContextSwitches.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Security.Claims;

namespace Microsoft.IdentityModel.Tokens
{
/// <summary>
/// AppContext switches for Microsoft.IdentityModel.Tokens and referencing packages.
/// </summary>
internal static class AppContextSwitches
{
/// <summary>
/// Enables a fallback to the previous behavior of using <see cref="ClaimsIdentity"/> instead of <see cref="CaseSensitiveClaimsIdentity"/> globally.
/// </summary>
internal const string UseClaimsIdentityTypeSwitch = "Microsoft.IdentityModel.Tokens.UseClaimsIdentityType";

internal static bool UseClaimsIdentityType() => (AppContext.TryGetSwitch(UseClaimsIdentityTypeSwitch, out bool useClaimsIdentityType) && useClaimsIdentityType);
}
}
109 changes: 109 additions & 0 deletions src/Microsoft.IdentityModel.Tokens/CaseSensitiveClaimsIdentity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Security.Claims;

namespace Microsoft.IdentityModel.Tokens
{
/// <summary>
/// A derived <see cref="ClaimsIdentity"/> where claim retrieval is case-sensitive. The current <see cref="ClaimsIdentity"/> retrieves claims in a case-insensitive manner which is different than querying the underlying <see cref="SecurityToken"/>. The <see cref="CaseSensitiveClaimsIdentity"/> provides consistent retrieval logic between the <see cref="SecurityToken"/> and <see cref="ClaimsIdentity"/>.
/// </summary>
public class CaseSensitiveClaimsIdentity : ClaimsIdentity
pmaytak marked this conversation as resolved.
Show resolved Hide resolved
{
/// <summary>
/// Initializes an instance of <see cref="CaseSensitiveClaimsIdentity"/>.
/// </summary>
public CaseSensitiveClaimsIdentity() : base()
{
}

/// <summary>
/// Initializes an instance of <see cref="CaseSensitiveClaimsIdentity"/>.
/// </summary>
/// <param name="claimsIdentity"><see cref="ClaimsIdentity"/> to copy.</param>
public CaseSensitiveClaimsIdentity(ClaimsIdentity claimsIdentity) : base(claimsIdentity)
{
}

/// <summary>
/// Initializes an instance of <see cref="CaseSensitiveClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
public CaseSensitiveClaimsIdentity(IEnumerable<Claim> claims) : base(claims)
{
}

/// <summary>
/// Initializes an instance of <see cref="CaseSensitiveClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
public CaseSensitiveClaimsIdentity(IEnumerable<Claim> claims, string authenticationType) : base(claims, authenticationType)
{
}

/// <summary>
/// Initializes an instance of <see cref="CaseSensitiveClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
public CaseSensitiveClaimsIdentity(IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType) :
base(claims, authenticationType, nameType, roleType)
{
}

/// <summary>
/// Initializes an instance of <see cref="CaseSensitiveClaimsIdentity"/>.
/// </summary>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
public CaseSensitiveClaimsIdentity(string authenticationType, string nameType, string roleType) :
base(authenticationType, nameType, roleType)
{
}

/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Comparison is: StringComparison.Ordinal.</remarks>
/// <exception cref="ArgumentNullException">if <paramref name="type"/> is null.</exception>
public override IEnumerable<Claim> FindAll(string type)
{
return base.FindAll(claim => claim?.Type.Equals(type, StringComparison.Ordinal) == true);
msbw2 marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
/// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="Claim"/>, <see langword="null"/> if nothing matches.</returns>
/// <remarks>Comparison is: StringComparison.Ordinal.</remarks>
/// <exception cref="ArgumentNullException">if <paramref name="type"/> is null.</exception>
public override Claim FindFirst(string type)
{
return base.FindFirst(claim => claim?.Type.Equals(type, StringComparison.Ordinal) == true);
}

/// <summary>
/// Determines if a claim with type AND value is contained within this claims identity.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <param name="value">The value of the claim to match.</param>
/// <returns><c>true</c> if a claim is matched, <c>false</c> otherwise.</returns>
/// <remarks>Comparison is: StringComparison.Ordinal for Claim.Type and Claim.Value.</remarks>
/// <exception cref="ArgumentNullException">if <paramref name="type"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="value"/> is null.</exception>
public override bool HasClaim(string type, string value)
{
return base.HasClaim(claim => claim?.Type.Equals(type, StringComparison.Ordinal) == true
&& claim?.Value.Equals(value, StringComparison.Ordinal) == true);
}
}
}
17 changes: 14 additions & 3 deletions src/Microsoft.IdentityModel.Tokens/TokenHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public abstract class TokenHandler
/// <exception cref="ArgumentOutOfRangeException">'value' less than 1.</exception>
public virtual int MaximumTokenSizeInBytes
{
get => _maximumTokenSizeInBytes;
set => _maximumTokenSizeInBytes = (value < 1) ? throw LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), FormatInvariant(LogMessages.IDX10101, MarkAsNonPII(value)))) : value;
get => _maximumTokenSizeInBytes;
set => _maximumTokenSizeInBytes = (value < 1) ? throw LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), FormatInvariant(LogMessages.IDX10101, MarkAsNonPII(value)))) : value;
}

/// <summary>
Expand All @@ -53,7 +53,6 @@ public int TokenLifetimeInMinutes
}

#region methods

/// <summary>
/// Validates a token.
/// On a validation failure, no exception will be thrown; instead, the exception will be set in the returned TokenValidationResult.Exception property.
Expand Down Expand Up @@ -125,6 +124,18 @@ internal virtual ClaimsIdentity CreateClaimsIdentityInternal(SecurityToken secur
MarkAsNonPII("internal virtual ClaimsIdentity CreateClaimsIdentityInternal(SecurityToken securityToken, TokenValidationParameters tokenValidationParameters, string issuer)"),
MarkAsNonPII(GetType().FullName))));
}

internal static ClaimsIdentity CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(SecurityToken securityToken, TokenValidationParameters validationParameters, string issuer)
pmaytak marked this conversation as resolved.
Show resolved Hide resolved
{
ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(securityToken, issuer);
msbw2 marked this conversation as resolved.
Show resolved Hide resolved

if (identity is not CaseSensitiveClaimsIdentity && !AppContextSwitches.UseClaimsIdentityType())
{
identity = new CaseSensitiveClaimsIdentity(identity);
}

return identity;
}
#endregion
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,10 @@ public virtual ClaimsIdentity CreateClaimsIdentity(SecurityToken securityToken,
if (LogHelper.IsEnabled(EventLogLevel.Informational))
LogHelper.LogInformation(LogMessages.IDX10245, securityToken);

return new ClaimsIdentity(authenticationType: AuthenticationType ?? DefaultAuthenticationType, nameType: nameClaimType ?? ClaimsIdentity.DefaultNameClaimType, roleType: roleClaimType ?? ClaimsIdentity.DefaultRoleClaimType);
if (AppContextSwitches.UseClaimsIdentityType())
pmaytak marked this conversation as resolved.
Show resolved Hide resolved
return new ClaimsIdentity(authenticationType: AuthenticationType ?? DefaultAuthenticationType, nameType: nameClaimType ?? ClaimsIdentity.DefaultNameClaimType, roleType: roleClaimType ?? ClaimsIdentity.DefaultRoleClaimType);
else
return new CaseSensitiveClaimsIdentity(authenticationType: AuthenticationType ?? DefaultAuthenticationType, nameType: nameClaimType ?? ClaimsIdentity.DefaultNameClaimType, roleType: roleClaimType ?? ClaimsIdentity.DefaultRoleClaimType);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ internal ClaimsIdentity ClaimsIdentityNoLocking
if (_validationParameters != null && SecurityToken != null && _tokenHandler != null && Issuer != null)
{
_claimsIdentity = _tokenHandler.CreateClaimsIdentityInternal(SecurityToken, _validationParameters, Issuer);
if (_claimsIdentity is not CaseSensitiveClaimsIdentity && !AppContextSwitches.UseClaimsIdentityType())
msbw2 marked this conversation as resolved.
Show resolved Hide resolved
_claimsIdentity = new CaseSensitiveClaimsIdentity(_claimsIdentity);
}

_claimsIdentityInitialized = true;
Expand Down
10 changes: 5 additions & 5 deletions src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1188,7 +1188,7 @@ private ClaimsPrincipal ValidateTokenPayload(JwtSecurityToken jwtToken, TokenVal

Validators.ValidateTokenType(jwtToken.Header.Typ, jwtToken, validationParameters);

var identity = CreateClaimsIdentity(jwtToken, issuer, validationParameters);
var identity = CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(jwtToken, validationParameters, issuer);
if (validationParameters.SaveSigninToken)
identity.BootstrapContext = jwtToken.RawData;

Expand All @@ -1198,9 +1198,9 @@ private ClaimsPrincipal ValidateTokenPayload(JwtSecurityToken jwtToken, TokenVal
return new ClaimsPrincipal(identity);
}

private ClaimsPrincipal CreateClaimsPrincipalFromToken(JwtSecurityToken jwtToken, string issuer, TokenValidationParameters validationParameters)
private static ClaimsPrincipal CreateClaimsPrincipalFromToken(JwtSecurityToken jwtToken, string issuer, TokenValidationParameters validationParameters)
{
var identity = CreateClaimsIdentity(jwtToken, issuer, validationParameters);
var identity = CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(jwtToken, validationParameters, issuer);
if (validationParameters.SaveSigninToken)
identity.BootstrapContext = jwtToken.RawData;

Expand Down Expand Up @@ -1527,7 +1527,7 @@ protected virtual ClaimsIdentity CreateClaimsIdentity(JwtSecurityToken jwtToken,

private ClaimsIdentity CreateClaimsIdentityWithMapping(JwtSecurityToken jwtToken, string actualIssuer, TokenValidationParameters validationParameters)
{
ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(jwtToken, actualIssuer);
ClaimsIdentity identity = CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(jwtToken, validationParameters, actualIssuer);
foreach (Claim jwtClaim in jwtToken.Claims)
{
if (_inboundClaimFilter.Contains(jwtClaim.Type))
Expand Down Expand Up @@ -1573,7 +1573,7 @@ private ClaimsIdentity CreateClaimsIdentityWithMapping(JwtSecurityToken jwtToken

private ClaimsIdentity CreateClaimsIdentityWithoutMapping(JwtSecurityToken jwtToken, string actualIssuer, TokenValidationParameters validationParameters)
{
ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(jwtToken, actualIssuer);
ClaimsIdentity identity = CreateCaseSensitiveClaimsIdentityFromTokenValidationParameters(jwtToken, validationParameters, actualIssuer);
foreach (Claim jwtClaim in jwtToken.Claims)
{
if (_inboundClaimFilter.Contains(jwtClaim.Type))
Expand Down
Loading
Loading