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

Fetch configuration when validating SAML issuer and signature #2412

Merged
merged 8 commits into from
Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.IdentityModel.Abstractions;
Expand Down Expand Up @@ -1139,6 +1140,9 @@ public override ClaimsPrincipal ValidateToken(XmlReader reader, TokenValidationP
if (validationParameters == null)
throw LogArgumentNullException(nameof(validationParameters));

validationParameters = SamlTokenUtilities.PopulateValidationParametersWithCurrentConfigurationAsync(validationParameters).ConfigureAwait(false).GetAwaiter()
.GetResult();

var samlToken = ReadSamlToken(reader);
if (samlToken == null)
throw LogExceptionMessage(
Expand All @@ -1150,25 +1154,41 @@ public override ClaimsPrincipal ValidateToken(XmlReader reader, TokenValidationP
}

/// <inheritdoc/>
public override Task<TokenValidationResult> ValidateTokenAsync(string token, TokenValidationParameters validationParameters)
public override async Task<TokenValidationResult> ValidateTokenAsync(string token, TokenValidationParameters validationParameters)
{
try
{
var claimsPrincipal = ValidateToken(token, validationParameters, out var validatedToken);
return Task.FromResult(new TokenValidationResult
if (string.IsNullOrWhiteSpace(token))
throw LogArgumentNullException(nameof(token));

if (validationParameters == null)
throw LogArgumentNullException(nameof(validationParameters));

if (token.Length > MaximumTokenSizeInBytes)
throw LogExceptionMessage(new ArgumentException(FormatInvariant(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes))));

validationParameters = await SamlTokenUtilities.PopulateValidationParametersWithCurrentConfigurationAsync(validationParameters).ConfigureAwait(false);

var samlToken = ValidateSignature(token, validationParameters);
if (samlToken == null)
throw LogExceptionMessage(new SecurityTokenValidationException(
FormatInvariant(TokenLogMessages.IDX10254, LogHelper.MarkAsNonPII(_className), LogHelper.MarkAsNonPII("ValidateToken"), LogHelper.MarkAsNonPII(GetType()), LogHelper.MarkAsNonPII("ValidateSignature"), LogHelper.MarkAsNonPII(typeof(SamlSecurityToken)))));

var claimsPrincipal = ValidateToken(samlToken, token, validationParameters, out var validatedToken);
return new TokenValidationResult
{
SecurityToken = validatedToken,
ClaimsIdentity = claimsPrincipal?.Identities.First(),
IsValid = true,
});
};
}
catch (Exception ex)
{
return Task.FromResult(new TokenValidationResult
return new TokenValidationResult
{
IsValid = false,
Exception = ex
});
};
}
}

Expand All @@ -1193,6 +1213,9 @@ public override ClaimsPrincipal ValidateToken(string token, TokenValidationParam
if (token.Length > MaximumTokenSizeInBytes)
throw LogExceptionMessage(new ArgumentException(FormatInvariant(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes))));

validationParameters = SamlTokenUtilities.PopulateValidationParametersWithCurrentConfigurationAsync(validationParameters).ConfigureAwait(false).GetAwaiter()
.GetResult();

var samlToken = ValidateSignature(token, validationParameters);
if (samlToken == null)
throw LogExceptionMessage(new SecurityTokenValidationException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
using System.Collections.Generic;
using Microsoft.IdentityModel.Xml;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Logging;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;

Expand Down Expand Up @@ -165,5 +168,29 @@ internal static string GetXsiTypeForValue(object value)

return null;
}

/// <summary>
/// Fetches current configuration from the ConfigurationManager of <paramref name="validationParameters"/>
/// and populates ValidIssuers and IssuerSigningKeys.
/// </summary>
/// <param name="validationParameters"> the token validation parameters to update.</param>
/// <returns> New TokenValidationParameters with ValidIssuers and IssuerSigningKeys updated.</returns>
internal static async Task<TokenValidationParameters> PopulateValidationParametersWithCurrentConfigurationAsync(
TokenValidationParameters validationParameters)
{
if (validationParameters.ConfigurationManager == null)
{
return validationParameters;
}

var currentConfiguration = await validationParameters.ConfigurationManager.GetBaseConfigurationAsync(CancellationToken.None).ConfigureAwait(false);
var validationParametersCloned = validationParameters.Clone();
var issuers = new[] { currentConfiguration.Issuer };

validationParametersCloned.ValidIssuers = (validationParametersCloned.ValidIssuers == null ? issuers : validationParametersCloned.ValidIssuers.Concat(issuers));
validationParametersCloned.IssuerSigningKeys = (validationParametersCloned.IssuerSigningKeys == null ? currentConfiguration.SigningKeys : validationParametersCloned.IssuerSigningKeys.Concat(currentConfiguration.SigningKeys));
return validationParametersCloned;

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.IdentityModel.Abstractions;
Expand Down Expand Up @@ -171,28 +172,45 @@ public virtual SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor
}

/// <inheritdoc/>
public override Task<TokenValidationResult> ValidateTokenAsync(string token, TokenValidationParameters validationParameters)
public override async Task<TokenValidationResult> ValidateTokenAsync(string token, TokenValidationParameters validationParameters)
{
try
{
var claimsPrincipal = ValidateToken(token, validationParameters, out var validatedToken);
return Task.FromResult(new TokenValidationResult
if (string.IsNullOrEmpty(token))
throw LogArgumentNullException(nameof(token));

if (validationParameters == null)
throw LogArgumentNullException(nameof(validationParameters));

if (token.Length > MaximumTokenSizeInBytes)
throw LogExceptionMessage(new ArgumentException(FormatInvariant(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes))));

validationParameters = await SamlTokenUtilities.PopulateValidationParametersWithCurrentConfigurationAsync(validationParameters).ConfigureAwait(false);

var samlToken = ValidateSignature(token, validationParameters);
if (samlToken == null)
throw LogExceptionMessage(
new SecurityTokenValidationException(FormatInvariant(TokenLogMessages.IDX10254, LogHelper.MarkAsNonPII(_className), LogHelper.MarkAsNonPII("ValidateToken"), LogHelper.MarkAsNonPII(_className), LogHelper.MarkAsNonPII("ValidateSignature"), LogHelper.MarkAsNonPII(typeof(Saml2SecurityToken)))));
var claimsPrincipal = ValidateToken(samlToken, token, validationParameters, out var validatedToken);
Hakon marked this conversation as resolved.
Show resolved Hide resolved

return new TokenValidationResult
{
SecurityToken = validatedToken,
ClaimsIdentity = claimsPrincipal?.Identities.First(),
IsValid = true,
});
};
}
catch (Exception ex)
{
return Task.FromResult(new TokenValidationResult
return new TokenValidationResult
{
IsValid = false,
Exception = ex
});
};
}
}


/// <summary>
/// Reads and validates a <see cref="Saml2SecurityToken"/>.
/// </summary>
Expand All @@ -212,6 +230,8 @@ public override ClaimsPrincipal ValidateToken(XmlReader reader, TokenValidationP
if (validationParameters == null)
throw LogArgumentNullException(nameof(validationParameters));

validationParameters = SamlTokenUtilities.PopulateValidationParametersWithCurrentConfigurationAsync(validationParameters).ConfigureAwait(false).GetAwaiter().GetResult();

var samlToken = ReadSaml2Token(reader);
if (samlToken == null)
throw LogExceptionMessage(
Expand All @@ -236,21 +256,14 @@ public override ClaimsPrincipal ValidateToken(XmlReader reader, TokenValidationP
/// <returns>A <see cref="ClaimsPrincipal"/> representing the identity contained in the token.</returns>
public override ClaimsPrincipal ValidateToken(string token, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
if (string.IsNullOrEmpty(token))
throw LogArgumentNullException(nameof(token));

if (validationParameters == null)
throw LogArgumentNullException(nameof(validationParameters));

if (token.Length > MaximumTokenSizeInBytes)
throw LogExceptionMessage(new ArgumentException(FormatInvariant(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes))));

var samlToken = ValidateSignature(token, validationParameters);
if (samlToken == null)
throw LogExceptionMessage(
new SecurityTokenValidationException(FormatInvariant(TokenLogMessages.IDX10254, LogHelper.MarkAsNonPII(_className), LogHelper.MarkAsNonPII("ValidateToken"), LogHelper.MarkAsNonPII(_className), LogHelper.MarkAsNonPII("ValidateSignature"), LogHelper.MarkAsNonPII(typeof(Saml2SecurityToken)))));
var tokenValidationResult = ValidateTokenAsync(token, validationParameters).ConfigureAwait(false).GetAwaiter().GetResult();
if (!tokenValidationResult.IsValid)
{
throw tokenValidationResult.Exception;
}

return ValidateToken(samlToken, token, validationParameters, out validatedToken);
validatedToken = tokenValidationResult.SecurityToken;
return new ClaimsPrincipal(tokenValidationResult.ClaimsIdentity);
}

private ClaimsPrincipal ValidateToken(Saml2SecurityToken samlToken, string token, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.WsFederation;
using Microsoft.IdentityModel.TestUtils;
using Microsoft.IdentityModel.Tokens.Saml.Tests;
using Microsoft.IdentityModel.Xml;
Expand Down Expand Up @@ -672,6 +674,63 @@ public static TheoryData<Saml2TheoryData> ValidateTokenTheoryData
Token = ReferenceTokens.Saml2Token_NoAttributes,
ValidationParameters = new TokenValidationParameters(),
},
new Saml2TheoryData("ReferenceTokens_Saml2Token_Valid_Issuer_ConfigurationManager")
{
ExpectedException = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10500:"),
Token = ReferenceTokens.Saml2Token_Valid,
ValidationParameters = new TokenValidationParameters
{
ConfigurationManager = new StaticConfigurationManager<BaseConfiguration>(new WsFederationConfiguration()
{
Issuer = "https://sts.windows.net/add29489-7269-41f4-8841-b63c95564420/",
}),
ValidateIssuerSigningKey = false,
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = false,
}
},
new Saml2TheoryData("ReferenceTokens_Saml2Token_Valid_IssuerSigningKey_ConfigurationManager")
Hakon marked this conversation as resolved.
Show resolved Hide resolved
{
Token = ReferenceTokens.Saml2Token_Valid,
ValidationParameters = new TokenValidationParameters
{
ConfigurationManager = new StaticConfigurationManager<BaseConfiguration>(new WsFederationConfiguration()
{
SigningKeys = { KeyingMaterial.DefaultAADSigningKey },
}),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
}
},
new Saml2TheoryData("ReferenceTokens_Saml2Token_Valid_IssuerSigningKey_and_Issuer_ConfigurationManager")
{
Token = ReferenceTokens.Saml2Token_Valid,
ValidationParameters = new TokenValidationParameters
{
ConfigurationManager = new StaticConfigurationManager<BaseConfiguration>(new WsFederationConfiguration()
{
Issuer = "https://sts.windows.net/add29489-7269-41f4-8841-b63c95564420/",
SigningKeys = { KeyingMaterial.DefaultAADSigningKey },
}),
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = false,
}
},
new Saml2TheoryData("ReferenceTokens_Saml2Token_Valid_NoSigningKey_ConfigurationManager")
{
ExpectedException = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10500:"),
Token = ReferenceTokens.Saml2Token_Valid,
ValidationParameters = new TokenValidationParameters
{
ConfigurationManager = new StaticConfigurationManager<BaseConfiguration>(new WsFederationConfiguration()),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
}
},
new Saml2TheoryData("ReferenceTokens_Saml2Token_Valid_IssuerSigningKey_set")
{
Token = ReferenceTokens.Saml2Token_Valid,
Expand Down
Loading
Loading