Skip to content

Commit

Permalink
Serialize byte arrays as base64 strings in JsonWebToken and JwtSecuri…
Browse files Browse the repository at this point in the history
…tyToken

Fixes #2524
  • Loading branch information
Keegan Caruso committed Jul 9, 2024
1 parent 1dd1e98 commit af80d45
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,10 @@ public static void WriteObject(ref Utf8JsonWriter writer, string key, object obj

writer.WriteEndObject();
}
else if ((typeof(byte[])).IsAssignableFrom(objType))
{
writer.WriteBase64String(key, (byte[])obj);
}
else if (typeof(IList).IsAssignableFrom(objType))
{
IList list = (IList)obj;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,33 @@ public class JsonWebTokenTests
new Claim("dateTimeIso8061", dateTime.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), ClaimValueTypes.DateTime, "LOCAL AUTHORITY", "LOCAL AUTHORITY"),
};

[Fact]
public void ByteArrayClaimsEncodedAsExpected()
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(new string('a', 128)));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var value = new byte[] { 0x21, 0x62, 0x36, 0x34 };

SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
SigningCredentials = creds,
Claims = new Dictionary<string, object>
{
["byteArray"] = value
},
};

JsonWebTokenHandler handler = new();
string tokenString = handler.CreateToken(tokenDescriptor);
JsonWebToken jsonWebToken = new JsonWebToken(tokenString);
var claimSet = jsonWebToken.Claims;
var expectedValue = System.Text.Json.JsonSerializer.Serialize(value).Trim('"');

// Will throw if can't find.
var testClaim = claimSet.First(c => c.Type == "byteArray");
Assert.Equal(expectedValue, testClaim.Value);
}

[Fact]
public void BoolClaimsEncodedAsExpected()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,28 @@ namespace System.IdentityModel.Tokens.Jwt.Tests
{
public class JwtSecurityTokenTests
{
[Fact]
public void ByteArrayClaimsEncodedAsExpected()
{
var value = new byte[] { 0x21, 0x62, 0x36, 0x34 };
var tokenPayload = new JwtPayload
{
["byteArray"] = value,
};

var token = new JwtSecurityToken(new JwtHeader(), tokenPayload);

var handler = new JwtSecurityTokenHandler();

var tokenString = handler.WriteToken(token);
var parsedToken = new JwtSecurityToken(tokenString);
var expectedValue = System.Text.Json.JsonSerializer.Serialize(value).Trim('"');

// Will throw if can't find.
var testClaim = parsedToken.Claims.First(c => c.Type == "byteArray");
Assert.Equal(expectedValue, testClaim.Value);
}

[Fact]
public void BoolClaimsEncodedAsExpected()
{
Expand Down

0 comments on commit af80d45

Please sign in to comment.