From e5272528a608b903e321223dd05f132d1d31a5dd Mon Sep 17 00:00:00 2001 From: Ignacio Inglese Date: Fri, 31 Jan 2025 00:20:38 +0000 Subject: [PATCH] Set the SigningKey in JsonWebToken only after the signature has been validated. Added test to prevent regressions. (#3111) --- .../JsonWebTokenHandler.ValidateSignature.cs | 6 ++++-- .../JsonWebTokenHandler.ValidateSignatureTests.cs | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.ValidateSignature.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.ValidateSignature.cs index 0b425260ea..cfcf05125c 100644 --- a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.ValidateSignature.cs +++ b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.ValidateSignature.cs @@ -104,8 +104,6 @@ internal static ValidationResult ValidateSignature( if (key is not null) { - jwtToken.SigningKey = key; - // If the key is found, validate the signature. return ValidateSignatureWithKey(jwtToken, key, validationParameters, callContext); } @@ -314,7 +312,11 @@ private static ValidationResult ValidateSignatureWithKey( ValidateSignature); if (valid) + { + jsonWebToken.SigningKey = key; + return key; + } else return new SignatureValidationError( new MessageDetail( diff --git a/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandler.ValidateSignatureTests.cs b/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandler.ValidateSignatureTests.cs index 2196c888bd..41ef472f65 100644 --- a/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandler.ValidateSignatureTests.cs +++ b/test/Microsoft.IdentityModel.JsonWebTokens.Tests/JsonWebTokenHandler.ValidateSignatureTests.cs @@ -66,6 +66,9 @@ public void ValidateSignature(JsonWebTokenHandlerValidateSignatureTheoryData the Exception exception = validationError.GetException(); theoryData.ExpectedException.ProcessException(exception, context); + + if (jsonWebToken is not null) + Assert.Null(jsonWebToken.SigningKey); } TestUtilities.AssertFailIfErrors(context);