diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs index 32ca7e462f..c58baa2015 100644 --- a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs +++ b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs @@ -9,6 +9,7 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; @@ -158,7 +159,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; } @@ -337,9 +340,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) @@ -354,7 +360,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; @@ -362,7 +368,7 @@ public virtual string CreateToken(SecurityTokenDescriptor tokenDescriptor) if (tokenDescriptor.Expires.HasValue) { - if (payload.ContainsKey(JwtRegisteredClaimNames.Exp)) + if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Exp)) LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.Expires)))); payload[JwtRegisteredClaimNames.Exp] = EpochTime.GetIntDate(tokenDescriptor.Expires.Value); @@ -370,7 +376,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; @@ -378,7 +384,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); @@ -386,7 +392,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); @@ -698,7 +704,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; @@ -841,7 +848,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; } @@ -1136,12 +1145,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); } @@ -1465,7 +1475,8 @@ private async ValueTask ValidateTokenAsync(JsonWebToken j { // 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())); } } @@ -1740,7 +1751,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; } @@ -1823,7 +1836,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; } @@ -1881,7 +1896,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 a7a4726fc0..ac8a03da34 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.Logging; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Linq; @@ -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 495da634cb..775841ed65 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.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 96c4f5d4dc..753c5dbd26 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.Logging; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; @@ -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 597dd47cb9..bb17d074ec 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.Logging; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; @@ -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 278e56df08..73e215909c 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.JsonWebTokens; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; @@ -1286,7 +1287,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) { @@ -1340,7 +1342,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 @@ internal static string GetToken(string wresult) { 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 virtual string GetTokenUsingXmlReader() { 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 5759413506..af0c251173 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 6f17203279..7bbb984e14 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 7d642bd359..323d197c19 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 d97e5c3b55..00ee2c023f 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 @@ -198,7 +199,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 6f0204d2e4..754ed570d3 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.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -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 2b270c22ff..a414f8c8ac 100644 --- a/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs +++ b/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; using Newtonsoft.Json; @@ -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 6c70134f37..e65cd49611 100644 --- a/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs +++ b/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security.Cryptography; +using Microsoft.IdentityModel.Abstractions; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens @@ -180,7 +181,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 @@ -231,7 +234,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 { @@ -377,7 +382,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 c98a01afdd..7f83c62d76 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 @@ -422,7 +423,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..ff4f096427 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,26 @@ 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); + 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); + keyInfo.RSAKeyValue = ReadRSAKeyValue(reader); + } + else + { + // Skip the element since it is not an + if (LogHelper.IsEnabled(EventLogLevel.Warning)) + { + LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml()); } else { - // Skip the element since it is not an - LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml()); + reader.Skip(); } + } // reader.ReadEndElement(); @@ -130,7 +138,14 @@ 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()); + } + else + { + reader.Skip(); + } } } @@ -195,7 +210,14 @@ 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()); + } + else + { + reader.Skip(); + } } } 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 b404f75298..da47d827f8 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; }