From 03fd778ee0cee6ded878172b8165acb7949166e0 Mon Sep 17 00:00:00 2001 From: Josh Lozensky Date: Tue, 28 May 2024 14:12:12 -0700 Subject: [PATCH] added a method to concat Audience and Audiences when writing to json --- .../JsonWebTokenHandler.CreateToken.cs | 14 +++++--------- .../Json/JsonSerializerPrimitives.cs | 11 ++++++++++- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.CreateToken.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.CreateToken.cs index 6678fe2bfe..a86e293ac1 100644 --- a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.CreateToken.cs +++ b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.CreateToken.cs @@ -708,23 +708,19 @@ internal static void WriteJwsPayload( if (!tokenDescriptor.Audiences.IsNullOrEmpty()) { - writer.WritePropertyName(JwtPayloadUtf8Bytes.Aud); - writer.WriteStartArray(); - foreach (string audience in tokenDescriptor.Audiences) { writer.WriteStringValue(audience); } - - if (!string.IsNullOrEmpty(tokenDescriptor.Audience)) - writer.WriteStringValue(tokenDescriptor.Audience); + if (!tokenDescriptor.Audience.IsNullOrEmpty()) + JsonPrimitives.WriteStrings(ref writer, JwtPayloadUtf8Bytes.Aud, tokenDescriptor.Audiences, tokenDescriptor.Audience); + else + JsonPrimitives.WriteStrings(ref writer, JwtPayloadUtf8Bytes.Aud, tokenDescriptor.Audiences); - writer.WriteEndArray(); audienceSet = true; } - else if (!string.IsNullOrEmpty(tokenDescriptor.Audience)) + else if (!tokenDescriptor.Audience.IsNullOrEmpty()) { writer.WritePropertyName(JwtPayloadUtf8Bytes.Aud); writer.WriteStringValue(tokenDescriptor.Audience); audienceSet = true; } - if (!string.IsNullOrEmpty(tokenDescriptor.Issuer)) { issuerSet = true; diff --git a/src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs b/src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs index 128ead5fa8..d57c3d4048 100644 --- a/src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs +++ b/src/Microsoft.IdentityModel.Tokens/Json/JsonSerializerPrimitives.cs @@ -1188,6 +1188,15 @@ public static void WriteStrings(ref Utf8JsonWriter writer, ReadOnlySpan pr writer.WriteEndArray(); } -#endregion + + public static void WriteStrings(ref Utf8JsonWriter writer, ReadOnlySpan propertyName, IList strings, string extraString) + { + writer.WriteStartArray(propertyName); + foreach (string str in strings) + writer.WriteStringValue(str); + writer.WriteStringValue(extraString); + writer.WriteEndArray(); + } + #endregion } }