From b48eb04ceaa76cd2df7d68912b2320a8633ae1c6 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Wed, 26 Jul 2023 09:31:47 -0400 Subject: [PATCH] Guard logging calls to avoid unnecessary work at call site Many LogHelper.Log calls are doing work at the call site, such as allocating params arrays, boxing structs, formatting strings, and so on, even when the data will be thrown away because logging (or logging for that verbosity level) isn't enabled. This adds an IsEnabled method to LogHelper and uses it at any call site where there's such work to be avoided. --- .../JsonWebTokenHandler.cs | 49 +++++++++++++------ .../JwtTokenUtilities.cs | 17 +++++-- .../LogHelper.cs | 26 +++++++--- .../TextWriterEventListener.cs | 5 +- .../OpenIdConnectConfiguration.cs | 9 +++- .../OpenIdConnectConfigurationRetriever.cs | 13 +++-- .../OpenIdConnectProtocolValidator.cs | 5 +- .../SignedHttpRequestHandler.cs | 7 ++- .../WsFederationMessage.cs | 24 ++++++--- .../Configuration/HttpDocumentRetriever.cs | 11 +++-- .../Saml/SamlSecurityTokenHandler.cs | 16 ++++-- .../Saml2/Saml2SecurityTokenHandler.cs | 15 ++++-- .../EventBasedLRUCache.cs | 10 ++-- .../InMemoryCryptoProviderCache.cs | 5 +- .../JsonWebKey.cs | 5 +- .../JsonWebKeyConverter.cs | 19 ++++--- .../JsonWebKeySet.cs | 5 +- .../SymmetricSignatureProvider.cs | 13 +++-- .../TokenValidationParameters.cs | 5 +- .../Validators.cs | 31 +++++++++--- .../DsigSerializer.cs | 32 ++++++------ .../JwtSecurityToken.cs | 3 +- .../JwtSecurityTokenHandler.cs | 31 +++++++++--- 23 files changed, 255 insertions(+), 101 deletions(-) diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs index b0cbe09581..7b088342e8 100644 --- a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs +++ b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs @@ -10,6 +10,7 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Json; using Microsoft.IdentityModel.Json.Linq; using Microsoft.IdentityModel.Logging; @@ -159,7 +160,9 @@ public virtual bool CanReadToken(string token) if (token.Length > MaximumTokenSizeInBytes) { - LogHelper.LogInformation(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes)); + return false; } @@ -327,9 +330,12 @@ public virtual string CreateToken(SecurityTokenDescriptor tokenDescriptor) if (tokenDescriptor == null) throw LogHelper.LogArgumentNullException(nameof(tokenDescriptor)); - if ((tokenDescriptor.Subject == null || !tokenDescriptor.Subject.Claims.Any()) - && (tokenDescriptor.Claims == null || !tokenDescriptor.Claims.Any())) - LogHelper.LogWarning(LogMessages.IDX14114, LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor)), LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor.Subject)), LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor.Claims))); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + { + if ((tokenDescriptor.Subject == null || !tokenDescriptor.Subject.Claims.Any()) + && (tokenDescriptor.Claims == null || !tokenDescriptor.Claims.Any())) + LogHelper.LogWarning(LogMessages.IDX14114, LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor)), LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor.Subject)), LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor.Claims))); + } JObject payload; if (tokenDescriptor.Subject != null) @@ -344,7 +350,7 @@ public virtual string CreateToken(SecurityTokenDescriptor tokenDescriptor) if (tokenDescriptor.Audience != null) { - if (payload.ContainsKey(JwtRegisteredClaimNames.Aud)) + if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Aud)) LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.Audience)))); payload[JwtRegisteredClaimNames.Aud] = tokenDescriptor.Audience; @@ -360,7 +366,7 @@ public virtual string CreateToken(SecurityTokenDescriptor tokenDescriptor) if (tokenDescriptor.Issuer != null) { - if (payload.ContainsKey(JwtRegisteredClaimNames.Iss)) + if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Iss)) LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.Issuer)))); payload[JwtRegisteredClaimNames.Iss] = tokenDescriptor.Issuer; @@ -368,7 +374,7 @@ public virtual string CreateToken(SecurityTokenDescriptor tokenDescriptor) if (tokenDescriptor.IssuedAt.HasValue) { - if (payload.ContainsKey(JwtRegisteredClaimNames.Iat)) + if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Iat)) LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.IssuedAt)))); payload[JwtRegisteredClaimNames.Iat] = EpochTime.GetIntDate(tokenDescriptor.IssuedAt.Value); @@ -376,7 +382,7 @@ public virtual string CreateToken(SecurityTokenDescriptor tokenDescriptor) if (tokenDescriptor.NotBefore.HasValue) { - if (payload.ContainsKey(JwtRegisteredClaimNames.Nbf)) + if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Nbf)) LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.NotBefore)))); payload[JwtRegisteredClaimNames.Nbf] = EpochTime.GetIntDate(tokenDescriptor.NotBefore.Value); @@ -688,7 +694,8 @@ private string CreateTokenPrivate( } catch(Exception ex) { - LogHelper.LogExceptionMessage(new SecurityTokenException(LogHelper.FormatInvariant(LogMessages.IDX14307, ex, payload))); + if (LogHelper.IsEnabled(EventLogLevel.Error)) + LogHelper.LogExceptionMessage(new SecurityTokenException(LogHelper.FormatInvariant(LogMessages.IDX14307, ex, payload))); } payload = jsonPayload != null ? jsonPayload.ToString(Formatting.None) : payload; @@ -831,7 +838,9 @@ private static string GetActualIssuer(JsonWebToken jwtToken) string actualIssuer = jwtToken.Issuer; if (string.IsNullOrWhiteSpace(actualIssuer)) { - LogHelper.LogVerbose(TokenLogMessages.IDX10244, ClaimsIdentity.DefaultIssuer); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(TokenLogMessages.IDX10244, ClaimsIdentity.DefaultIssuer); + actualIssuer = ClaimsIdentity.DefaultIssuer; } @@ -1126,12 +1135,13 @@ internal IEnumerable GetContentEncryptionKeys(JsonWebToken jwtToken var key = ResolveTokenDecryptionKey(jwtToken.EncodedToken, jwtToken, validationParameters); if (key != null) { - LogHelper.LogInformation(TokenLogMessages.IDX10904, key); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10904, key); } else if (configuration != null) { key = ResolveTokenDecryptionKeyFromConfig(jwtToken, configuration); - if ( key != null ) + if (key != null && LogHelper.IsEnabled(EventLogLevel.Informational)) LogHelper.LogInformation(TokenLogMessages.IDX10905, key); } @@ -1455,7 +1465,8 @@ private async Task ValidateTokenAsync(JsonWebToken jsonWe { // The exception is not re-thrown as the TokenValidationParameters may have the issuer and signing key set // directly on them, allowing the library to continue with token validation. - LogHelper.LogWarning(LogHelper.FormatInvariant(TokenLogMessages.IDX10261, validationParameters.ConfigurationManager.MetadataAddress, ex.ToString())); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(TokenLogMessages.IDX10261, validationParameters.ConfigurationManager.MetadataAddress, ex.ToString())); } } @@ -1731,7 +1742,9 @@ private static JsonWebToken ValidateSignature(JsonWebToken jwtToken, TokenValida { if (ValidateSignature(jwtToken, key, validationParameters)) { - LogHelper.LogInformation(TokenLogMessages.IDX10242, jwtToken); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10242, jwtToken); + jwtToken.SigningKey = key; return jwtToken; } @@ -1813,7 +1826,9 @@ internal static bool ValidateSignature(byte[] encodedBytes, byte[] signature, Se var cryptoProviderFactory = validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory; if (!cryptoProviderFactory.IsSupportedAlgorithm(algorithm, key)) { - LogHelper.LogInformation(LogMessages.IDX14000, LogHelper.MarkAsNonPII(algorithm), key); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX14000, LogHelper.MarkAsNonPII(algorithm), key); + return false; } @@ -1871,7 +1886,9 @@ internal static bool ValidateSignature(JsonWebToken jsonWebToken, SecurityKey ke var cryptoProviderFactory = validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory; if (!cryptoProviderFactory.IsSupportedAlgorithm(jsonWebToken.Alg, key)) { - LogHelper.LogInformation(LogMessages.IDX14000, LogHelper.MarkAsNonPII(jsonWebToken.Alg), key); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX14000, LogHelper.MarkAsNonPII(jsonWebToken.Alg), key); + return false; } diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs index 80cc999c7e..809c8f98d1 100644 --- a/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs +++ b/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs @@ -10,6 +10,7 @@ using System.Text; using System.Text.Json; using System.Text.RegularExpressions; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Json.Linq; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; @@ -97,7 +98,9 @@ public static string CreateEncodedSignature(string input, SigningCredentials sig try { - LogHelper.LogVerbose(LogHelper.FormatInvariant(LogMessages.IDX14201, LogHelper.MarkAsNonPII(cacheProvider))); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogHelper.FormatInvariant(LogMessages.IDX14201, LogHelper.MarkAsNonPII(cacheProvider))); + return Base64UrlEncoder.Encode(signatureProvider.Sign(Encoding.UTF8.GetBytes(input))); } finally @@ -165,7 +168,9 @@ internal static string DecryptJwtToken( var cryptoProviderFactory = validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory; if (cryptoProviderFactory == null) { - LogHelper.LogWarning(TokenLogMessages.IDX10607, key); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(TokenLogMessages.IDX10607, key); + continue; } @@ -179,8 +184,10 @@ internal static string DecryptJwtToken( { if (!cryptoProviderFactory.IsSupportedAlgorithm(jsonWebToken.Enc, key)) { + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(TokenLogMessages.IDX10611, LogHelper.MarkAsNonPII(decryptionParameters.Enc), key); + algorithmNotSupportedByCryptoProvider = true; - LogHelper.LogWarning(TokenLogMessages.IDX10611, LogHelper.MarkAsNonPII(decryptionParameters.Enc), key); continue; } @@ -203,8 +210,10 @@ internal static string DecryptJwtToken( { if (!cryptoProviderFactory.IsSupportedAlgorithm(decryptionParameters.Enc, key)) { + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(TokenLogMessages.IDX10611, LogHelper.MarkAsNonPII(decryptionParameters.Enc), key); + algorithmNotSupportedByCryptoProvider = true; - LogHelper.LogWarning(TokenLogMessages.IDX10611, LogHelper.MarkAsNonPII(decryptionParameters.Enc), key); continue; } diff --git a/src/Microsoft.IdentityModel.Logging/LogHelper.cs b/src/Microsoft.IdentityModel.Logging/LogHelper.cs index 40f3006562..5e177ae210 100644 --- a/src/Microsoft.IdentityModel.Logging/LogHelper.cs +++ b/src/Microsoft.IdentityModel.Logging/LogHelper.cs @@ -42,6 +42,15 @@ internal static bool HeaderWritten set { _isHeaderWritten = value; } } + /// + /// Gets whether logging is enabled at the specified ."/> + /// + /// The log level + /// if logging is enabled at the specified level; otherwise, . + public static bool IsEnabled(EventLogLevel level) => + Logger.IsEnabled(level) || + IdentityModelEventSource.Logger.IsEnabled(EventLogLevelToEventLevel(level), EventKeywords.All); + /// /// Logs an exception using the event source logger and returns new exception. /// @@ -255,7 +264,7 @@ public static Exception LogExceptionMessage(EventLevel eventLevel, Exception exc if (exception == null) return null; - if (IdentityModelEventSource.Logger.IsEnabled() && IdentityModelEventSource.Logger.LogLevel >= eventLevel) + if (IdentityModelEventSource.Logger.IsEnabled(eventLevel, EventKeywords.All)) IdentityModelEventSource.Logger.Write(eventLevel, exception.InnerException, exception.Message); EventLogLevel eventLogLevel = EventLevelToEventLogLevel(eventLevel); @@ -272,7 +281,7 @@ public static Exception LogExceptionMessage(EventLevel eventLevel, Exception exc /// An object array that contains zero or more objects to format. public static void LogInformation(string message, params object[] args) { - if (IdentityModelEventSource.Logger.IsEnabled() && IdentityModelEventSource.Logger.LogLevel >= EventLevel.Informational) + if (IdentityModelEventSource.Logger.IsEnabled(EventLevel.Informational, EventKeywords.All)) IdentityModelEventSource.Logger.WriteInformation(message, args); if (Logger.IsEnabled(EventLogLevel.Informational)) @@ -286,8 +295,8 @@ public static void LogInformation(string message, params object[] args) /// An object array that contains zero or more objects to format. public static void LogVerbose(string message, params object[] args) { - if (IdentityModelEventSource.Logger.IsEnabled()) - IdentityModelEventSource.Logger.WriteVerbose(message, args); + if (IdentityModelEventSource.Logger.IsEnabled(EventLevel.Verbose, EventKeywords.All)) + IdentityModelEventSource.Logger.WriteVerbose(message, args); if (Logger.IsEnabled(EventLogLevel.Verbose)) Logger.Log(WriteEntry((EventLogLevel)EventLevel.Verbose, null, message, args)); @@ -300,8 +309,8 @@ public static void LogVerbose(string message, params object[] args) /// An object array that contains zero or more objects to format. public static void LogWarning(string message, params object[] args) { - if (IdentityModelEventSource.Logger.IsEnabled()) - IdentityModelEventSource.Logger.WriteWarning(message, args); + if (IdentityModelEventSource.Logger.IsEnabled(EventLevel.Warning, EventKeywords.All)) + IdentityModelEventSource.Logger.WriteWarning(message, args); if (Logger.IsEnabled(EventLogLevel.Warning)) Logger.Log(WriteEntry(EventLogLevel.Warning, null, message, args)); @@ -323,7 +332,7 @@ public static void LogWarning(string message, params object[] args) else message = format; - if (IdentityModelEventSource.Logger.IsEnabled() && IdentityModelEventSource.Logger.LogLevel >= eventLevel) + if (IdentityModelEventSource.Logger.IsEnabled(eventLevel, EventKeywords.All)) IdentityModelEventSource.Logger.Write(eventLevel, innerException, message); EventLogLevel eventLogLevel = EventLevelToEventLogLevel(eventLevel); @@ -345,6 +354,9 @@ public static void LogWarning(string message, params object[] args) private static EventLogLevel EventLevelToEventLogLevel(EventLevel eventLevel) => (uint)(int)eventLevel <= 5 ? (EventLogLevel)eventLevel : EventLogLevel.Error; + private static EventLevel EventLogLevelToEventLevel(EventLogLevel eventLevel) => + (uint)(int)eventLevel <= 5 ? (EventLevel)eventLevel : EventLevel.Error; + /// /// Formats the string using InvariantCulture /// diff --git a/src/Microsoft.IdentityModel.Logging/TextWriterEventListener.cs b/src/Microsoft.IdentityModel.Logging/TextWriterEventListener.cs index c56c1fca07..d6414495de 100644 --- a/src/Microsoft.IdentityModel.Logging/TextWriterEventListener.cs +++ b/src/Microsoft.IdentityModel.Logging/TextWriterEventListener.cs @@ -4,6 +4,7 @@ using System; using System.Diagnostics.Tracing; using System.IO; +using Microsoft.IdentityModel.Abstractions; namespace Microsoft.IdentityModel.Logging { @@ -31,7 +32,7 @@ public TextWriterEventListener() _streamWriter = new StreamWriter(fileStream); _streamWriter.AutoFlush = true; } - catch (Exception ex) + catch (Exception ex) when (LogHelper.IsEnabled(EventLogLevel.Error)) { LogHelper.LogExceptionMessage(new InvalidOperationException(LogMessages.MIML10001, ex)); throw; @@ -53,7 +54,7 @@ public TextWriterEventListener(string filePath) _streamWriter = new StreamWriter(fileStream); _streamWriter.AutoFlush = true; } - catch (Exception ex) + catch (Exception ex) when (LogHelper.IsEnabled(EventLogLevel.Error)) { LogHelper.LogExceptionMessage(new InvalidOperationException(LogMessages.MIML10001, ex)); throw; diff --git a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfiguration.cs b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfiguration.cs index 77252a50fc..9011b86036 100644 --- a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfiguration.cs +++ b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfiguration.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Json; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; @@ -31,7 +32,9 @@ public static OpenIdConnectConfiguration Create(string json) if (string.IsNullOrEmpty(json)) throw LogHelper.LogArgumentNullException(nameof(json)); - LogHelper.LogVerbose(LogMessages.IDX21808, json); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX21808, json); + return new OpenIdConnectConfiguration(json); } @@ -69,7 +72,9 @@ public OpenIdConnectConfiguration(string json) try { - LogHelper.LogVerbose(LogMessages.IDX21806, json, LogHelper.MarkAsNonPII(_className)); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX21806, json, LogHelper.MarkAsNonPII(_className)); + JsonConvert.PopulateObject(json, this); } catch (Exception ex) diff --git a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfigurationRetriever.cs b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfigurationRetriever.cs index 10704df74e..4d1b4e5dbe 100644 --- a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfigurationRetriever.cs +++ b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfigurationRetriever.cs @@ -4,6 +4,7 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Json; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; @@ -64,14 +65,20 @@ public static async Task GetAsync(string address, ID string doc = await retriever.GetDocumentAsync(address, cancel).ConfigureAwait(false); - LogHelper.LogVerbose(LogMessages.IDX21811, doc); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX21811, doc); + OpenIdConnectConfiguration openIdConnectConfiguration = JsonConvert.DeserializeObject(doc); if (!string.IsNullOrEmpty(openIdConnectConfiguration.JwksUri)) { - LogHelper.LogVerbose(LogMessages.IDX21812, openIdConnectConfiguration.JwksUri); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX21812, openIdConnectConfiguration.JwksUri); + string keys = await retriever.GetDocumentAsync(openIdConnectConfiguration.JwksUri, cancel).ConfigureAwait(false); - LogHelper.LogVerbose(LogMessages.IDX21813, openIdConnectConfiguration.JwksUri); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX21813, openIdConnectConfiguration.JwksUri); + openIdConnectConfiguration.JsonWebKeySet = JsonConvert.DeserializeObject(keys); foreach (SecurityKey key in openIdConnectConfiguration.JsonWebKeySet.GetSigningKeys()) { diff --git a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/OpenIdConnectProtocolValidator.cs b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/OpenIdConnectProtocolValidator.cs index 814d892314..b7384698f5 100644 --- a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/OpenIdConnectProtocolValidator.cs +++ b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/OpenIdConnectProtocolValidator.cs @@ -8,6 +8,7 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Cryptography; using System.Text; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; @@ -457,7 +458,9 @@ public CryptoProviderFactory CryptoProviderFactory /// If expected value does not equal the hashed value. private void ValidateHash(string expectedValue, string hashItem, string algorithm) { - LogHelper.LogInformation(LogMessages.IDX21303, expectedValue); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX21303, expectedValue); + HashAlgorithm hashAlgorithm = null; try { diff --git a/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs b/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs index 5f5a4962ff..86c215d7a2 100644 --- a/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs +++ b/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs @@ -32,6 +32,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Json; using Microsoft.IdentityModel.Json.Linq; using Microsoft.IdentityModel.JsonWebTokens; @@ -1279,7 +1280,8 @@ private static Dictionary SanitizeQueryParams(Uri httpRequestUri if (repeatedQueryParams.Any()) { - LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX23004, LogHelper.MarkAsNonPII(string.Join(", ", repeatedQueryParams)))); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX23004, LogHelper.MarkAsNonPII(string.Join(", ", repeatedQueryParams)))); foreach (var repeatedQueryParam in repeatedQueryParams) { @@ -1333,7 +1335,8 @@ private static Dictionary SanitizeHeaders(IDictionaryIf 'queryString' is null or whitespace, a default is returned. Parameters are parsed from . public static WsFederationMessage FromQueryString(string queryString) { - LogHelper.LogVerbose(FormatInvariant(LogMessages.IDX22900, queryString)); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(FormatInvariant(LogMessages.IDX22900, queryString)); var wsFederationMessage = new WsFederationMessage(); if (!string.IsNullOrWhiteSpace(queryString)) @@ -61,7 +63,9 @@ public static WsFederationMessage FromUri(Uri uri) { if (uri != null && uri.Query.Length > 1) { - LogHelper.LogVerbose(FormatInvariant(LogMessages.IDX22901, uri.ToString())); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(FormatInvariant(LogMessages.IDX22901, uri.ToString())); + return FromQueryString(uri.Query.Substring(1)); } @@ -76,7 +80,9 @@ public WsFederationMessage(WsFederationMessage wsFederationMessage) { if (wsFederationMessage == null) { - LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, LogHelper.MarkAsNonPII(nameof(wsFederationMessage)))); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, LogHelper.MarkAsNonPII(nameof(wsFederationMessage)))); + return; } @@ -94,7 +100,9 @@ public WsFederationMessage(IEnumerable> parameter { if (parameters == null) { - LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, LogHelper.MarkAsNonPII(nameof(parameters)))); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, LogHelper.MarkAsNonPII(nameof(parameters)))); + return; } @@ -153,7 +161,9 @@ public string CreateSignOutUrl() { if (string.IsNullOrEmpty(wresult)) { - LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, LogHelper.MarkAsNonPII(nameof(wresult)))); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, LogHelper.MarkAsNonPII(nameof(wresult)))); + return null; } @@ -221,7 +231,9 @@ public string CreateSignOutUrl() { if (Wresult == null) { - LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, LogHelper.MarkAsNonPII(nameof(Wresult)))); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(FormatInvariant(LogMessages.IDX22000, LogHelper.MarkAsNonPII(nameof(Wresult)))); + return null; } diff --git a/src/Microsoft.IdentityModel.Protocols/Configuration/HttpDocumentRetriever.cs b/src/Microsoft.IdentityModel.Protocols/Configuration/HttpDocumentRetriever.cs index 4789c9beea..ac4c759fbf 100644 --- a/src/Microsoft.IdentityModel.Protocols/Configuration/HttpDocumentRetriever.cs +++ b/src/Microsoft.IdentityModel.Protocols/Configuration/HttpDocumentRetriever.cs @@ -8,6 +8,7 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; @@ -92,7 +93,9 @@ public async Task GetDocumentAsync(string address, CancellationToken can HttpResponseMessage response; try { - LogHelper.LogVerbose(LogMessages.IDX20805, address); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX20805, address); + var httpClient = _httpClient ?? _defaultHttpClient; var uri = new Uri(address, UriKind.RelativeOrAbsolute); response = await SendAsyncAndRetryOnNetworkError(httpClient, uri).ConfigureAwait(false); @@ -131,12 +134,14 @@ private async Task SendAsyncAndRetryOnNetworkError(HttpClie if (response.StatusCode.Equals(HttpStatusCode.RequestTimeout) || response.StatusCode.Equals(HttpStatusCode.ServiceUnavailable)) { - if (i < maxAttempt) // logging exception details and that we will attempt to retry document retrieval + if (i < maxAttempt && LogHelper.IsEnabled(EventLogLevel.Informational)) // logging exception details and that we will attempt to retry document retrieval LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX20808, response.StatusCode, await response.Content.ReadAsStringAsync().ConfigureAwait(false), message.RequestUri)); } else // if the exception type does not indicate the need to retry we should break { - LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX20809, message.RequestUri, response.StatusCode, await response.Content.ReadAsStringAsync().ConfigureAwait(false))); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX20809, message.RequestUri, response.StatusCode, await response.Content.ReadAsStringAsync().ConfigureAwait(false))); + break; } } diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.cs index 874ecf1722..dd235bb038 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.cs @@ -10,6 +10,7 @@ using System.Text; using System.Threading.Tasks; using System.Xml; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; using static Microsoft.IdentityModel.Logging.LogHelper; using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages; @@ -335,7 +336,9 @@ protected virtual IEnumerable CreateClaimsIdentities(SamlSecurit var actualIssuer = issuer; if (string.IsNullOrWhiteSpace(issuer)) { - LogHelper.LogVerbose(TokenLogMessages.IDX10244, LogHelper.MarkAsNonPII(ClaimsIdentity.DefaultIssuer)); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(TokenLogMessages.IDX10244, LogHelper.MarkAsNonPII(ClaimsIdentity.DefaultIssuer)); + actualIssuer = ClaimsIdentity.DefaultIssuer; } @@ -616,7 +619,8 @@ protected virtual void ProcessCustomSubjectStatement(SamlStatement statement, Cl if (statement == null) throw LogArgumentNullException(nameof(statement)); - LogHelper.LogWarning(LogMessages.IDX11516, LogHelper.MarkAsNonPII(statement.GetType())); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogMessages.IDX11516, LogHelper.MarkAsNonPII(statement.GetType())); } /// @@ -1058,7 +1062,10 @@ private SamlSecurityToken ValidateSignature(SamlSecurityToken samlToken, string Validators.ValidateAlgorithm(samlToken.Assertion.Signature.SignedInfo.SignatureMethod, key, samlToken, validationParameters); samlToken.Assertion.Signature.Verify(key, validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory); - LogHelper.LogInformation(TokenLogMessages.IDX10242, token); + + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10242, token); + samlToken.SigningKey = key; return samlToken; } @@ -1210,7 +1217,8 @@ private ClaimsPrincipal ValidateToken(SamlSecurityToken samlToken, string token, identities.ElementAt(0).BootstrapContext = samlToken.Assertion.CanonicalString; } - LogHelper.LogInformation(TokenLogMessages.IDX10241, token); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10241, token); return new ClaimsPrincipal(identities); } diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.cs index 30c37eea29..e9f3ff72e1 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.cs @@ -10,6 +10,7 @@ using System.Text; using System.Threading.Tasks; using System.Xml; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens.Saml; using static Microsoft.IdentityModel.Logging.LogHelper; @@ -267,7 +268,8 @@ private ClaimsPrincipal ValidateToken(Saml2SecurityToken samlToken, string token if (validationParameters.SaveSigninToken) identity.BootstrapContext = samlToken.Assertion.CanonicalString; - LogHelper.LogInformation(TokenLogMessages.IDX10241, token); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10241, token); return new ClaimsPrincipal(identity); } @@ -440,7 +442,10 @@ private Saml2SecurityToken ValidateSignature(Saml2SecurityToken samlToken, strin Validators.ValidateAlgorithm(samlToken.Assertion.Signature.SignedInfo.SignatureMethod, key, samlToken, validationParameters); samlToken.Assertion.Signature.Verify(key, validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory); - LogHelper.LogInformation(TokenLogMessages.IDX10242, token); + + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10242, token); + samlToken.SigningKey = key; return samlToken; } @@ -1125,7 +1130,7 @@ protected virtual void ProcessStatements(ICollection statements, ProcessAuthenticationStatement(authnStatement, identity, issuer); else if (statement is Saml2AuthorizationDecisionStatement authzStatement) ProcessAuthorizationDecisionStatement(authzStatement, identity, issuer); - else + else if (LogHelper.IsEnabled(EventLogLevel.Warning)) LogWarning(LogMessages.IDX13516, LogHelper.MarkAsNonPII(statement.GetType())); } } @@ -1281,7 +1286,9 @@ protected virtual ClaimsIdentity CreateClaimsIdentity(Saml2SecurityToken samlTok var actualIssuer = issuer; if (string.IsNullOrWhiteSpace(issuer)) { - LogHelper.LogVerbose(TokenLogMessages.IDX10244, LogHelper.MarkAsNonPII(ClaimsIdentity.DefaultIssuer)); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(TokenLogMessages.IDX10244, LogHelper.MarkAsNonPII(ClaimsIdentity.DefaultIssuer)); + actualIssuer = ClaimsIdentity.DefaultIssuer; } diff --git a/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs b/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs index fa417848d4..497a91cbeb 100644 --- a/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs +++ b/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs @@ -8,6 +8,7 @@ using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens @@ -227,7 +228,8 @@ private void EventQueueTaskAction() } catch (Exception ex) { - LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10900, ex)); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10900, ex)); } } @@ -261,7 +263,8 @@ internal int RemoveExpiredValuesLRU() } catch (ObjectDisposedException ex) { - LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10902, LogHelper.MarkAsNonPII(nameof(RemoveExpiredValuesLRU)), ex)); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10902, LogHelper.MarkAsNonPII(nameof(RemoveExpiredValuesLRU)), ex)); } return numItemsRemoved; @@ -290,7 +293,8 @@ internal int RemoveExpiredValues() } catch (ObjectDisposedException ex) { - LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10902, LogHelper.MarkAsNonPII(nameof(RemoveExpiredValues)), ex)); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10902, LogHelper.MarkAsNonPII(nameof(RemoveExpiredValues)), ex)); } return numItemsRemoved; diff --git a/src/Microsoft.IdentityModel.Tokens/InMemoryCryptoProviderCache.cs b/src/Microsoft.IdentityModel.Tokens/InMemoryCryptoProviderCache.cs index 37b91bf4ab..7c5d64c63d 100644 --- a/src/Microsoft.IdentityModel.Tokens/InMemoryCryptoProviderCache.cs +++ b/src/Microsoft.IdentityModel.Tokens/InMemoryCryptoProviderCache.cs @@ -4,6 +4,7 @@ using System; using System.Globalization; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens @@ -203,7 +204,9 @@ public override bool TryRemove(SignatureProvider signatureProvider) } catch (Exception ex) { - LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10699, cacheKey, ex)); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10699, cacheKey, ex)); + return false; } } diff --git a/src/Microsoft.IdentityModel.Tokens/JsonWebKey.cs b/src/Microsoft.IdentityModel.Tokens/JsonWebKey.cs index c00ef45cd8..747250ff44 100644 --- a/src/Microsoft.IdentityModel.Tokens/JsonWebKey.cs +++ b/src/Microsoft.IdentityModel.Tokens/JsonWebKey.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Security.Cryptography; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Json; using Microsoft.IdentityModel.Json.Linq; using Microsoft.IdentityModel.Logging; @@ -54,7 +55,9 @@ public JsonWebKey(string json) try { - LogHelper.LogVerbose(LogMessages.IDX10806, json, LogHelper.MarkAsNonPII(_className)); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX10806, json, LogHelper.MarkAsNonPII(_className)); + JsonConvert.PopulateObject(json, this); } catch (Exception ex) diff --git a/src/Microsoft.IdentityModel.Tokens/JsonWebKeyConverter.cs b/src/Microsoft.IdentityModel.Tokens/JsonWebKeyConverter.cs index f51bbbb63d..337e94baeb 100644 --- a/src/Microsoft.IdentityModel.Tokens/JsonWebKeyConverter.cs +++ b/src/Microsoft.IdentityModel.Tokens/JsonWebKeyConverter.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Security.Cryptography; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens @@ -228,10 +229,12 @@ internal static bool TryConvertToSecurityKey(JsonWebKey webKey, out SecurityKey } catch (Exception ex) { - LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10813, LogHelper.MarkAsNonPII(typeof(SecurityKey)), webKey, ex)); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10813, LogHelper.MarkAsNonPII(typeof(SecurityKey)), webKey, ex)); } - LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10812, LogHelper.MarkAsNonPII(typeof(SecurityKey)), webKey)); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(LogMessages.IDX10812, LogHelper.MarkAsNonPII(typeof(SecurityKey)), webKey)); return false; } @@ -255,7 +258,8 @@ internal static bool TryConvertToSymmetricSecurityKey(JsonWebKey webKey, out Sec } catch(Exception ex) { - LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10813, LogHelper.MarkAsNonPII(typeof(SymmetricSecurityKey)), webKey, ex), ex)); + if (LogHelper.IsEnabled(EventLogLevel.Error)) + LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10813, LogHelper.MarkAsNonPII(typeof(SymmetricSecurityKey)), webKey, ex), ex)); } return false; @@ -284,7 +288,8 @@ internal static bool TryConvertToX509SecurityKey(JsonWebKey webKey, out Security { string convertKeyInfo = LogHelper.FormatInvariant(LogMessages.IDX10813, LogHelper.MarkAsNonPII(typeof(X509SecurityKey)), webKey, ex); webKey.ConvertKeyInfo = convertKeyInfo; - LogHelper.LogExceptionMessage(new InvalidOperationException(convertKeyInfo, ex)); + if (LogHelper.IsEnabled(EventLogLevel.Error)) + LogHelper.LogExceptionMessage(new InvalidOperationException(convertKeyInfo, ex)); } return false; @@ -311,7 +316,8 @@ internal static bool TryCreateToRsaSecurityKey(JsonWebKey webKey, out SecurityKe { string convertKeyInfo = LogHelper.FormatInvariant(LogMessages.IDX10813, LogHelper.MarkAsNonPII(typeof(RsaSecurityKey)), webKey, ex); webKey.ConvertKeyInfo = convertKeyInfo; - LogHelper.LogExceptionMessage(new InvalidOperationException(convertKeyInfo, ex)); + if (LogHelper.IsEnabled(EventLogLevel.Error)) + LogHelper.LogExceptionMessage(new InvalidOperationException(convertKeyInfo, ex)); } return false; @@ -351,7 +357,8 @@ internal static bool TryConvertToECDsaSecurityKey(JsonWebKey webKey, out Securit { string convertKeyInfo = LogHelper.FormatInvariant(LogMessages.IDX10813, LogHelper.MarkAsNonPII(typeof(ECDsaSecurityKey)), webKey, ex); webKey.ConvertKeyInfo = convertKeyInfo; - LogHelper.LogExceptionMessage(new InvalidOperationException(convertKeyInfo, ex)); + if (LogHelper.IsEnabled(EventLogLevel.Error)) + LogHelper.LogExceptionMessage(new InvalidOperationException(convertKeyInfo, ex)); } return false; diff --git a/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs b/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs index a9e4a7cc2d..913e090035 100644 --- a/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs +++ b/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs @@ -6,6 +6,7 @@ using System.ComponentModel; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Json; +using Microsoft.IdentityModel.Abstractions; namespace Microsoft.IdentityModel.Tokens { @@ -53,7 +54,9 @@ public JsonWebKeySet(string json) try { - LogHelper.LogVerbose(LogMessages.IDX10806, json, LogHelper.MarkAsNonPII(_className)); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX10806, json, LogHelper.MarkAsNonPII(_className)); + JsonConvert.PopulateObject(json, this); } catch (Exception ex) diff --git a/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs b/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs index b7b98bcadb..9e341620db 100644 --- a/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs +++ b/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Security.Cryptography; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens @@ -178,7 +179,9 @@ public override byte[] Sign(byte[] input) throw LogHelper.LogExceptionMessage(new ObjectDisposedException(GetType().ToString())); } - LogHelper.LogInformation(LogMessages.IDX10642, input); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10642, input); + KeyedHashAlgorithm keyedHashAlgorithm = GetKeyedHashAlgorithm(GetKeyBytes(Key), Algorithm); try @@ -229,7 +232,9 @@ public override bool Verify(byte[] input, byte[] signature) throw LogHelper.LogExceptionMessage(new ObjectDisposedException(GetType().ToString())); } - LogHelper.LogInformation(LogMessages.IDX10643, input); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10643, input); + KeyedHashAlgorithm keyedHashAlgorithm = GetKeyedHashAlgorithm(GetKeyBytes(Key), Algorithm); try { @@ -372,7 +377,9 @@ internal bool Verify(byte[] input, int inputOffset, int inputLength, byte[] sign throw LogHelper.LogExceptionMessage(new ObjectDisposedException(GetType().ToString())); } - LogHelper.LogInformation(LogMessages.IDX10643, input); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10643, input); + KeyedHashAlgorithm keyedHashAlgorithm = null; try { diff --git a/src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs b/src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs index cf40db0b45..dfa48069dd 100644 --- a/src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs +++ b/src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs @@ -6,6 +6,7 @@ using System.ComponentModel; using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens @@ -421,7 +422,9 @@ public virtual ClaimsIdentity CreateClaimsIdentity(SecurityToken securityToken, roleClaimType = RoleClaimType; } - LogHelper.LogInformation(LogMessages.IDX10245, 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); } diff --git a/src/Microsoft.IdentityModel.Tokens/Validators.cs b/src/Microsoft.IdentityModel.Tokens/Validators.cs index 20e76450e7..dccc32a547 100644 --- a/src/Microsoft.IdentityModel.Tokens/Validators.cs +++ b/src/Microsoft.IdentityModel.Tokens/Validators.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens @@ -133,7 +134,9 @@ private static bool AudienceIsValid(IEnumerable audiences, TokenValidati if (AudiencesMatch(validationParameters, tokenAudience, validAudience)) { - LogHelper.LogInformation(LogMessages.IDX10234, LogHelper.MarkAsNonPII(tokenAudience)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10234, LogHelper.MarkAsNonPII(tokenAudience)); + return true; } } @@ -170,7 +173,9 @@ private static bool AudiencesMatchIgnoringTrailingSlash(string tokenAudience, st if (string.CompareOrdinal(validAudience, 0, tokenAudience, 0, length) == 0) { - LogHelper.LogInformation(LogMessages.IDX10234, LogHelper.MarkAsNonPII(tokenAudience)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10234, LogHelper.MarkAsNonPII(tokenAudience)); + return true; } @@ -266,14 +271,18 @@ internal static async Task ValidateIssuerAsync( { if (string.Equals(configuration.Issuer, issuer)) { - LogHelper.LogInformation(LogMessages.IDX10236, LogHelper.MarkAsNonPII(issuer)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10236, LogHelper.MarkAsNonPII(issuer)); + return issuer; } } if (string.Equals(validationParameters.ValidIssuer, issuer)) { - LogHelper.LogInformation(LogMessages.IDX10236, LogHelper.MarkAsNonPII(issuer)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10236, LogHelper.MarkAsNonPII(issuer)); + return issuer; } @@ -289,7 +298,9 @@ internal static async Task ValidateIssuerAsync( if (string.Equals(str, issuer)) { - LogHelper.LogInformation(LogMessages.IDX10236, LogHelper.MarkAsNonPII(issuer)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10236, LogHelper.MarkAsNonPII(issuer)); + return issuer; } } @@ -393,12 +404,14 @@ internal static void ValidateIssuerSigningKeyLifeTime(SecurityKey securityKey, T if (notBeforeUtc > DateTimeUtil.Add(utcNow, validationParameters.ClockSkew)) throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidSigningKeyException(LogHelper.FormatInvariant(LogMessages.IDX10248, LogHelper.MarkAsNonPII(notBeforeUtc), LogHelper.MarkAsNonPII(utcNow)))); - LogHelper.LogInformation(LogMessages.IDX10250, LogHelper.MarkAsNonPII(notBeforeUtc), LogHelper.MarkAsNonPII(utcNow)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10250, LogHelper.MarkAsNonPII(notBeforeUtc), LogHelper.MarkAsNonPII(utcNow)); if (notAfterUtc < DateTimeUtil.Add(utcNow, validationParameters.ClockSkew.Negate())) throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidSigningKeyException(LogHelper.FormatInvariant(LogMessages.IDX10249, LogHelper.MarkAsNonPII(notAfterUtc), LogHelper.MarkAsNonPII(utcNow)))); - LogHelper.LogInformation(LogMessages.IDX10251, LogHelper.MarkAsNonPII(notAfterUtc), LogHelper.MarkAsNonPII(utcNow)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10251, LogHelper.MarkAsNonPII(notAfterUtc), LogHelper.MarkAsNonPII(utcNow)); } } @@ -562,7 +575,9 @@ public static string ValidateTokenType(string type, SecurityToken securityToken, } // if it reaches here, token type was succcessfully validated. - LogHelper.LogInformation(LogMessages.IDX10258, LogHelper.MarkAsNonPII(type)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX10258, LogHelper.MarkAsNonPII(type)); + return type; } } diff --git a/src/Microsoft.IdentityModel.Xml/DsigSerializer.cs b/src/Microsoft.IdentityModel.Xml/DsigSerializer.cs index 6e371fd1ea..7cdc75e853 100644 --- a/src/Microsoft.IdentityModel.Xml/DsigSerializer.cs +++ b/src/Microsoft.IdentityModel.Xml/DsigSerializer.cs @@ -6,6 +6,7 @@ using System.IO; using System.Text; using System.Xml; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; using static Microsoft.IdentityModel.Logging.LogHelper; @@ -110,19 +111,20 @@ public virtual KeyInfo ReadKeyInfo(XmlReader reader) else if (reader.IsStartElement(XmlSignatureConstants.Elements.KeyValue, XmlSignatureConstants.Namespace)) { reader.ReadStartElement(XmlSignatureConstants.Elements.KeyValue, XmlSignatureConstants.Namespace); - if (reader.IsStartElement(XmlSignatureConstants.Elements.RSAKeyValue, XmlSignatureConstants.Namespace)) - { - // Multiple RSAKeyValues were found - if (keyInfo.RSAKeyValue != null) - throw XmlUtil.LogReadException(LogMessages.IDX30015, XmlSignatureConstants.Elements.RSAKeyValue); - - keyInfo.RSAKeyValue = ReadRSAKeyValue(reader); - } - else - { - // Skip the element since it is not an + if (reader.IsStartElement(XmlSignatureConstants.Elements.RSAKeyValue, XmlSignatureConstants.Namespace)) + { + // Multiple RSAKeyValues were found + if (keyInfo.RSAKeyValue != null) + throw XmlUtil.LogReadException(LogMessages.IDX30015, XmlSignatureConstants.Elements.RSAKeyValue); + + keyInfo.RSAKeyValue = ReadRSAKeyValue(reader); + } + else + { + // Skip the element since it is not an + if (LogHelper.IsEnabled(EventLogLevel.Warning)) LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml()); - } + } // reader.ReadEndElement(); @@ -130,7 +132,8 @@ public virtual KeyInfo ReadKeyInfo(XmlReader reader) else { // Skip the element since it is not one of , , - LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml()); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml()); } } @@ -195,7 +198,8 @@ private static X509Data ReadX509Data(XmlReader reader) else { // Skip the element since it is not one of , , , , - LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml()); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml()); } } diff --git a/src/System.IdentityModel.Tokens.Jwt/JwtSecurityToken.cs b/src/System.IdentityModel.Tokens.Jwt/JwtSecurityToken.cs index 29cb41b233..861b76094f 100644 --- a/src/System.IdentityModel.Tokens.Jwt/JwtSecurityToken.cs +++ b/src/System.IdentityModel.Tokens.Jwt/JwtSecurityToken.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Security.Claims; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; @@ -505,7 +506,7 @@ internal void Decode(string[] tokenParts, string rawData) private void DecodeJws(string[] tokenParts) { // Log if CTY is set, assume compact JWS - if (Header.Cty != null) + if (Header.Cty != null && LogHelper.IsEnabled(EventLogLevel.Verbose)) LogHelper.LogVerbose(LogHelper.FormatInvariant(LogMessages.IDX12738, Header.Cty)); try diff --git a/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs b/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs index 9d2e617d44..c4c89765fc 100644 --- a/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs +++ b/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using System.Xml; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; @@ -281,7 +282,9 @@ public override bool CanReadToken(string token) if (token.Length > MaximumTokenSizeInBytes) { - LogHelper.LogInformation(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes)); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes)); + return false; } @@ -639,7 +642,9 @@ private JwtSecurityToken CreateJwtSecurityTokenPrivate( notBefore = now; } - LogHelper.LogVerbose(LogMessages.IDX12721, LogHelper.MarkAsNonPII(issuer ?? "null"), LogHelper.MarkAsNonPII(audience ?? "null")); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(LogMessages.IDX12721, LogHelper.MarkAsNonPII(issuer ?? "null"), LogHelper.MarkAsNonPII(audience ?? "null")); + JwtPayload payload = new JwtPayload(issuer, audience, (subject == null ? null : OutboundClaimTypeTransform(subject.Claims)), (claimCollection == null ? null : OutboundClaimTypeTransform(claimCollection)), notBefore, expires, issuedAt); JwtHeader header = new JwtHeader(signingCredentials, OutboundAlgorithmMap, tokenType, additionalInnerHeaderClaims); @@ -651,7 +656,8 @@ private JwtSecurityToken CreateJwtSecurityTokenPrivate( string message = string.Concat(header.Base64UrlEncode(), ".", payload.Base64UrlEncode()); string rawSignature = signingCredentials == null ? string.Empty : JwtTokenUtilities.CreateEncodedSignature(message, signingCredentials); - LogHelper.LogInformation(LogMessages.IDX12722, rawHeader, rawPayload, rawSignature); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(LogMessages.IDX12722, rawHeader, rawPayload, rawSignature); if (encryptingCredentials != null) { @@ -884,7 +890,8 @@ private ClaimsPrincipal ValidateToken(string token, JwtSecurityToken outerToken, { // The exception is not re-thrown as the TokenValidationParameters may have the issuer and signing key set // directly on them, allowing the library to continue with token validation. - LogHelper.LogWarning(LogHelper.FormatInvariant(TokenLogMessages.IDX10261, LogHelper.MarkAsNonPII(validationParameters.ConfigurationManager.MetadataAddress), ex.ToString())); + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + LogHelper.LogWarning(LogHelper.FormatInvariant(TokenLogMessages.IDX10261, LogHelper.MarkAsNonPII(validationParameters.ConfigurationManager.MetadataAddress), ex.ToString())); } } @@ -1158,7 +1165,9 @@ private ClaimsPrincipal ValidateTokenPayload(JwtSecurityToken jwtToken, TokenVal if (validationParameters.SaveSigninToken) identity.BootstrapContext = jwtToken.RawData; - LogHelper.LogInformation(TokenLogMessages.IDX10241, jwtToken); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10241, jwtToken); + return new ClaimsPrincipal(identity); } @@ -1168,7 +1177,9 @@ private ClaimsPrincipal CreateClaimsPrincipalFromToken(JwtSecurityToken jwtToken if (validationParameters.SaveSigninToken) identity.BootstrapContext = jwtToken.RawData; - LogHelper.LogInformation(TokenLogMessages.IDX10241, jwtToken); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10241, jwtToken); + return new ClaimsPrincipal(identity); } @@ -1364,7 +1375,9 @@ private JwtSecurityToken ValidateSignature(string token, JwtSecurityToken jwtTok { if (ValidateSignature(encodedBytes, signatureBytes, key, jwtToken.Header.Alg, jwtToken, validationParameters)) { - LogHelper.LogInformation(TokenLogMessages.IDX10242, jwtToken); + if (LogHelper.IsEnabled(EventLogLevel.Informational)) + LogHelper.LogInformation(TokenLogMessages.IDX10242, jwtToken); + jwtToken.SigningKey = key; return jwtToken; } @@ -1460,7 +1473,9 @@ protected virtual ClaimsIdentity CreateClaimsIdentity(JwtSecurityToken jwtToken, var actualIssuer = issuer; if (string.IsNullOrWhiteSpace(issuer)) { - LogHelper.LogVerbose(TokenLogMessages.IDX10244, LogHelper.MarkAsNonPII(ClaimsIdentity.DefaultIssuer)); + if (LogHelper.IsEnabled(EventLogLevel.Verbose)) + LogHelper.LogVerbose(TokenLogMessages.IDX10244, LogHelper.MarkAsNonPII(ClaimsIdentity.DefaultIssuer)); + actualIssuer = ClaimsIdentity.DefaultIssuer; }