Claims identity and principal debugging update (#87742)
authorJames Newton-King <james@newtonking.com>
Mon, 19 Jun 2023 02:05:48 +0000 (10:05 +0800)
committerGitHub <noreply@github.com>
Mon, 19 Jun 2023 02:05:48 +0000 (22:05 -0400)
* Claims identity and principal debugging update

* Comment

src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs
src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs

index 406fa2138bc3db45b9d61db914e12607de1b3fd4..e0d82df3b7863f3ae9b0074beab388b9ea50ff31 100644 (file)
@@ -946,7 +946,21 @@ namespace System.Security.Claims
                 claimsCount++;
             }
 
-            return $"Identity Name = {Name ?? "(null)"}, IsAuthenticated = {(IsAuthenticated ? "true" : "false")}, Claims Count = {claimsCount}";
+            string debugText = $"IsAuthenticated = {(IsAuthenticated ? "true" : "false")}";
+            if (Name != null)
+            {
+                // The ClaimsIdentity.Name property requires that ClaimsIdentity.NameClaimType is correctly
+                // configured to match the name of the logical name claim type of the identity.
+                // Because of this, only include name if the ClaimsIdentity.Name property has a value.
+                // Not including the name is to avoid developer confusion at seeing "Name = (null)" on an authenticated identity.
+                debugText += $", Name = {Name}";
+            }
+            if (claimsCount > 0)
+            {
+                debugText += $", Claims = {claimsCount}";
+            }
+
+            return debugText;
         }
 
         private sealed class ClaimsIdentityDebugProxy
index 1e1efd8eba62682ef0c1e75df6da7ce2b3152ac1..13ee10f7f6f4e69827828deeaf8cd674b97b78d8 100644 (file)
@@ -580,19 +580,19 @@ namespace System.Security.Claims
                 identitiesCount++;
             }
 
-            int claimsCount = 0;
-            foreach (Claim item in Claims)
+            // Return debug string optimized for the case of one identity.
+            if (identitiesCount == 1 && Identity is ClaimsIdentity claimsIdentity)
             {
-                claimsCount++;
+                return claimsIdentity.DebuggerToString();
             }
 
-            // Return debug string optimized for the case of one identity.
-            if (identitiesCount == 1 && Identity is ClaimsIdentity claimsIdentity)
+            int claimsCount = 0;
+            foreach (Claim item in Claims)
             {
-                return $"Principal {claimsIdentity.DebuggerToString()}";
+                claimsCount++;
             }
 
-            return $"Principal Identities Count: {identitiesCount}, Claims Count: {claimsCount}";
+            return $"Identities = {identitiesCount}, Claims = {claimsCount}";
         }
 
         private sealed class ClaimsPrincipalDebugProxy