Skip to content

Commit

Permalink
Remove unnecessary string.Split in JsonWebTokenHandler.CanReadToken (#…
Browse files Browse the repository at this point in the history
…2175)

We can count the number of periods instead of allocating a string for each segment and a string[] to store them all in.
  • Loading branch information
stephentoub authored and brentschmaltz committed Sep 7, 2023
1 parent 0f97085 commit 37cfe17
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -162,17 +162,28 @@ public virtual bool CanReadToken(string token)
return false;
}

// Set the maximum number of segments to MaxJwtSegmentCount + 1. This controls the number of splits and allows detecting the number of segments is too large.
// For example: "a.b.c.d.e.f.g.h" => [a], [b], [c], [d], [e], [f.g.h]. 6 segments.
// If just MaxJwtSegmentCount was used, then [a], [b], [c], [d], [e.f.g.h] would be returned. 5 segments.
int tokenPartCount = JwtTokenUtilities.CountJwtTokenPart(token, JwtConstants.MaxJwtSegmentCount + 1);
if (tokenPartCount == JwtConstants.JwsSegmentCount)
return JwtTokenUtilities.RegexJws.IsMatch(token);
else if (tokenPartCount == JwtConstants.JweSegmentCount)
return JwtTokenUtilities.RegexJwe.IsMatch(token);

LogHelper.LogInformation(LogMessages.IDX14107);
return false;
// Count the number of segments, which is the number of periods + 1. We can stop when we've encountered
// more segments than the maximum we know how to handle.
int pos = 0;
int segmentCount = 1; // TODO: Use MemoryExtensions.Count in .NET 8
while (segmentCount <= JwtConstants.MaxJwtSegmentCount && ((pos = token.IndexOf('.', pos)) >= 0))
{
pos++;
segmentCount++;
}

switch (segmentCount)
{
case JwtConstants.JwsSegmentCount:
return JwtTokenUtilities.RegexJws.IsMatch(token);

case JwtConstants.JweSegmentCount:
return JwtTokenUtilities.RegexJwe.IsMatch(token);

default:
LogHelper.LogInformation(LogMessages.IDX14107);
return false;
}
}

/// <summary>
Expand Down

0 comments on commit 37cfe17

Please sign in to comment.