Safe Token Logging in .NET Applications
When handling tokens in .NET applications, it's essential to avoid logging them in full due to the potential exposure of sensitive information. A best practice is to redact tokens before logging by showing only a prefix and/or suffix.
Here’s a robust approach:
-
Redact tokens safely: Display only the first few and last few characters of the token, separated by ellipses (
...
). If the token is too short to show both, consider showing only the prefix followed by...
, or return a standardized warning. -
Implement a helper method: Encapsulate redaction logic in a shared utility to ensure consistent and secure usage throughout the codebase.
public static string RedactToken(string token, int prefixLength = 6, int suffixLength = 4)
{
if (string.IsNullOrEmpty(token))
return "[null or empty token]";
int minLengthForFullRedaction = prefixLength + suffixLength;
if (token.Length >= minLengthForFullRedaction)
{
var prefix = token.Substring(0, prefixLength);
var suffix = token.Substring(token.Length - suffixLength);
return $"{prefix}...{suffix}";
}
int minLengthForPrefixOnly = prefixLength + 3; // For "..."
if (token.Length >= minLengthForPrefixOnly)
{
var prefix = token.Substring(0, prefixLength);
return $"{prefix}...";
}
return "[token too short to redact securely]";
}
-
Optional hashing for debugging: If correlation is needed without revealing the token, hash it using a secure algorithm (e.g., SHA256) and log only the hash.
By centralizing redaction in a reusable helper and applying consistent rules, applications can balance debugging needs with security best practices.
Comments