-
Notifications
You must be signed in to change notification settings - Fork 434
Validate Issuer Using New Validation Model in Saml2SecurityTokenHandler #2929
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
Merged
FuPingFranco
merged 13 commits into
dev
from
francofung/ImplementIssuerValidationInSaml2WithNewModel
Oct 23, 2024
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
fa4db37
Initial changes to include Issuer validation to Saml2SecurityTokenHan…
fbcb1ce
Clean-up
1dc6695
Merge branch 'dev' into francofung/ImplementIssuerValidationInSaml2Wi…
FuPingFranco 8059645
Merge branch 'francofung/ImplementIssuerValidationInSaml2WithNewModel…
510c182
Cache issuer validation failed stackframe
4773b52
Use WsFedConfig instead
99b260e
Merge branch 'dev' into francofung/ImplementIssuerValidationInSaml2Wi…
iNinja 386399e
Merge branch 'dev' into francofung/ImplementIssuerValidationInSaml2Wi…
FuPingFranco 18e5a15
Merge branch 'dev' into francofung/ImplementIssuerValidationInSaml2Wi…
FuPingFranco 8cdc28b
Addressing PR feedback
d86ef91
Merge branch 'dev' into francofung/ImplementIssuerValidationInSaml2Wi…
FuPingFranco 1ac5e32
Merge branch 'dev' into francofung/ImplementIssuerValidationInSaml2Wi…
iNinja a3ed270
Update src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilitie…
FuPingFranco File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
212 changes: 212 additions & 0 deletions
212
...yModel.Tokens.Saml.Tests/Saml2SecurityTokenHandlerTests.ValidateTokenAsyncTests.Issuer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,212 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.IdentityModel.Protocols.WsFederation; | ||
using Microsoft.IdentityModel.TestUtils; | ||
using Microsoft.IdentityModel.Tokens.Saml2; | ||
using Xunit; | ||
|
||
namespace Microsoft.IdentityModel.Tokens.Saml.Tests | ||
{ | ||
#nullable enable | ||
public partial class Saml2SecurityTokenHandlerTests | ||
{ | ||
[Theory, MemberData(nameof(ValidateTokenAsync_IssuerTestCases), DisableDiscoveryEnumeration = true)] | ||
public async Task ValidateTokenAsync_IssuerComparison(ValidateTokenAsyncIssuerTheoryData theoryData) | ||
{ | ||
var context = TestUtilities.WriteHeader($"{this}.ValidateTokenAsync_IssuerComparison", theoryData); | ||
|
||
var saml2Token = CreateTokenWithIssuer(theoryData.TokenIssuer); | ||
|
||
var tokenValidationParameters = CreateTokenValidationParametersForIssuerValidationOnly( | ||
saml2Token, | ||
theoryData.NullTokenValidationParameters, | ||
theoryData.ValidationParametersIssuer, | ||
theoryData.ConfigurationIssuer); | ||
|
||
Saml2SecurityTokenHandler saml2TokenHandler = new Saml2SecurityTokenHandler(); | ||
|
||
// Validate token using TokenValidationParameters | ||
TokenValidationResult tokenValidationResult = | ||
await saml2TokenHandler.ValidateTokenAsync(saml2Token.Assertion.CanonicalString, tokenValidationParameters); | ||
|
||
// Validate token using ValidationParameters. | ||
ValidationResult<ValidatedToken> validationResult = | ||
await saml2TokenHandler.ValidateTokenAsync( | ||
saml2Token, | ||
theoryData.ValidationParameters!, | ||
theoryData.CallContext, | ||
CancellationToken.None); | ||
|
||
// Ensure validity of the results match the expected result. | ||
if (tokenValidationResult.IsValid != validationResult.IsValid) | ||
{ | ||
context.AddDiff($"tokenValidationResult.IsValid != validationResult.IsSuccess"); | ||
theoryData.ExpectedExceptionValidationParameters!.ProcessException(validationResult.UnwrapError().GetException(), context); | ||
theoryData.ExpectedException.ProcessException(tokenValidationResult.Exception, context); | ||
} | ||
else | ||
{ | ||
if (tokenValidationResult.IsValid) | ||
{ | ||
// Verify validated tokens from both paths match. | ||
ValidatedToken validatedToken = validationResult.UnwrapResult(); | ||
IdentityComparer.AreEqual(validatedToken.SecurityToken, tokenValidationResult.SecurityToken, context); | ||
} | ||
else | ||
{ | ||
// Verify the exception provided by both paths match. | ||
var tokenValidationResultException = tokenValidationResult.Exception; | ||
theoryData.ExpectedException.ProcessException(tokenValidationResult.Exception, context); | ||
var validationResultException = validationResult.UnwrapError().GetException(); | ||
theoryData.ExpectedExceptionValidationParameters!.ProcessException(validationResult.UnwrapError().GetException(), context); | ||
} | ||
|
||
TestUtilities.AssertFailIfErrors(context); | ||
} | ||
} | ||
|
||
public static TheoryData<ValidateTokenAsyncIssuerTheoryData> ValidateTokenAsync_IssuerTestCases | ||
{ | ||
get | ||
{ | ||
var theoryData = new TheoryData<ValidateTokenAsyncIssuerTheoryData>(); | ||
|
||
theoryData.Add(new ValidateTokenAsyncIssuerTheoryData("Valid_IssuerIsValidIssuer") | ||
{ | ||
TokenIssuer = Default.Issuer, | ||
ValidationParametersIssuer = Default.Issuer, | ||
ValidationParameters = CreateValidationParameters(validIssuer: Default.Issuer), | ||
}); | ||
|
||
theoryData.Add(new ValidateTokenAsyncIssuerTheoryData("Valid_IssuerIsConfigurationIssuer") | ||
{ | ||
TokenIssuer = Default.Issuer, | ||
ConfigurationIssuer = Default.Issuer, | ||
ValidationParameters = CreateValidationParameters(configurationIssuer: Default.Issuer), | ||
}); | ||
|
||
theoryData.Add(new ValidateTokenAsyncIssuerTheoryData("Invalid_IssuerIsNotValid") | ||
{ | ||
TokenIssuer = "InvalidIssuer", | ||
ValidationParametersIssuer = Default.Issuer, | ||
ValidationParameters = CreateValidationParameters(validIssuer: Default.Issuer), | ||
ExpectedIsValid = false, | ||
ExpectedException = new ExpectedException(typeof(SecurityTokenInvalidIssuerException), "IDX10205:"), | ||
ExpectedExceptionValidationParameters = new ExpectedException(typeof(SecurityTokenInvalidIssuerException), "IDX10212:") | ||
}); | ||
|
||
theoryData.Add(new ValidateTokenAsyncIssuerTheoryData("Invalid_IssuerIsWhitespace") | ||
{ | ||
//This test will cover the case where the issuer is null or empty as well since, we do not allow tokens to be created with null or empty issuer. | ||
TokenIssuer = " ", | ||
ValidationParametersIssuer = Default.Issuer, | ||
ValidationParameters = CreateValidationParameters(validIssuer: Default.Issuer), | ||
ExpectedIsValid = false, | ||
ExpectedException = new ExpectedException(typeof(SecurityTokenInvalidIssuerException), "IDX10211:") | ||
}); | ||
|
||
theoryData.Add(new ValidateTokenAsyncIssuerTheoryData("Invalid_NoValidIssuersProvided") | ||
{ | ||
TokenIssuer = Default.Issuer, | ||
ValidationParametersIssuer = string.Empty, | ||
ValidationParameters = CreateValidationParameters(), | ||
ExpectedIsValid = false, | ||
ExpectedException = new ExpectedException(typeof(SecurityTokenInvalidIssuerException), "IDX10204:"), | ||
ExpectedExceptionValidationParameters = new ExpectedException(typeof(SecurityTokenInvalidIssuerException), "IDX10211:") | ||
}); | ||
|
||
return theoryData; | ||
|
||
static ValidationParameters CreateValidationParameters( | ||
string? validIssuer = null, | ||
string? configurationIssuer = null) | ||
{ | ||
ValidationParameters validationParameters = new ValidationParameters(); | ||
|
||
// Skip all validations except issuer | ||
validationParameters.AlgorithmValidator = SkipValidationDelegates.SkipAlgorithmValidation; | ||
validationParameters.AudienceValidator = SkipValidationDelegates.SkipAudienceValidation; | ||
validationParameters.LifetimeValidator = SkipValidationDelegates.SkipLifetimeValidation; | ||
validationParameters.IssuerSigningKeyValidator = SkipValidationDelegates.SkipIssuerSigningKeyValidation; | ||
validationParameters.SignatureValidator = SkipValidationDelegates.SkipSignatureValidation; | ||
|
||
return validationParameters; | ||
} | ||
} | ||
} | ||
|
||
public class ValidateTokenAsyncIssuerTheoryData : TheoryDataBase | ||
{ | ||
public ValidateTokenAsyncIssuerTheoryData(string testId) : base(testId) { } | ||
|
||
internal ValidationParameters? ValidationParameters { get; set; } | ||
|
||
internal ExpectedException? ExpectedExceptionValidationParameters { get; set; } = ExpectedException.NoExceptionExpected; | ||
|
||
internal bool ExpectedIsValid { get; set; } = true; | ||
|
||
public bool NullTokenValidationParameters { get; internal set; } = false; | ||
|
||
public string? TokenIssuer { get; set; } | ||
|
||
public string? ValidationParametersIssuer { get; set; } = null; | ||
|
||
public string? ConfigurationIssuer { get; set; } = null; | ||
} | ||
|
||
private static Saml2SecurityToken CreateTokenWithIssuer(string? issuer) | ||
{ | ||
Saml2SecurityTokenHandler saml2TokenHandler = new Saml2SecurityTokenHandler(); | ||
|
||
SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor | ||
{ | ||
SigningCredentials = Default.AsymmetricSigningCredentials, | ||
Audience = Default.Audience, | ||
Issuer = issuer, | ||
Subject = Default.SamlClaimsIdentity | ||
}; | ||
|
||
return (Saml2SecurityToken)saml2TokenHandler.CreateToken(securityTokenDescriptor); | ||
} | ||
|
||
private static TokenValidationParameters? CreateTokenValidationParametersForIssuerValidationOnly( | ||
Saml2SecurityToken saml2SecurityToken, | ||
bool nullTokenValidationParameters, | ||
string? validIssuer, | ||
string? configurationIssuer) | ||
{ | ||
if (nullTokenValidationParameters) | ||
{ | ||
return null; | ||
} | ||
|
||
var tokenValidationParameters = new TokenValidationParameters() | ||
{ | ||
ValidateAudience = false, | ||
ValidateIssuer = false, | ||
ValidateLifetime = false, | ||
ValidateTokenReplay = false, | ||
ValidateIssuerSigningKey = false, | ||
IssuerSigningKey = Default.AsymmetricSigningKey, | ||
ValidAudiences = [Default.Audience], | ||
ValidIssuer = validIssuer, | ||
SignatureValidator = delegate (string token, TokenValidationParameters validationParameters) | ||
{ | ||
return saml2SecurityToken; | ||
} | ||
}; | ||
|
||
if (configurationIssuer is not null) | ||
{ | ||
var validConfig = new WsFederationConfiguration() { Issuer = configurationIssuer }; | ||
tokenValidationParameters.ConfigurationManager = new MockConfigurationManager<WsFederationConfiguration>(validConfig); | ||
} | ||
|
||
return tokenValidationParameters; | ||
} | ||
} | ||
} | ||
#nullable restore |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.