Skip to content

Commit

Permalink
Fix roles checking from new identity-based token handler
Browse files Browse the repository at this point in the history
The roles in JWT aren't mapped to the namespaced role, and we want to keep it that way for consistency with the bare JWT `roles`.

By extending the ClaimsPrincipal we return from manifest reading, we can maintain compatibility with minimal changes.

See Azure/azure-functions-host#3898, for example.
  • Loading branch information
kzu committed Jun 29, 2024
1 parent 7febebc commit 6eecf46
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/SponsorLink/SponsorLink/SponsorLink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public static bool TryRead([NotNullWhen(true)] out ClaimsPrincipal? principal, I
if (Validate(value.jwt, value.jwk, out var token, out var identity, false) == ManifestStatus.Valid && identity != null)
{
if (principal == null)
principal = new(identity);
principal = new JwtRolesPrincipal(identity);
else
principal.AddIdentity(identity);
}
Expand Down Expand Up @@ -158,7 +158,7 @@ public static ManifestStatus Validate(string jwt, string jwk, out SecurityToken?
}

token = result.SecurityToken;
identity = new ClaimsIdentity(result.ClaimsIdentity.Claims);
identity = new ClaimsIdentity(result.ClaimsIdentity.Claims, "JWT");

if (validateExpiration && token.ValidTo == DateTime.MinValue)
return ManifestStatus.Invalid;
Expand All @@ -169,4 +169,9 @@ public static ManifestStatus Validate(string jwt, string jwk, out SecurityToken?

return ManifestStatus.Valid;
}

class JwtRolesPrincipal(ClaimsIdentity identity) : ClaimsPrincipal([identity])
{
public override bool IsInRole(string role) => HasClaim("roles", role) || base.IsInRole(role);
}
}

0 comments on commit 6eecf46

Please sign in to comment.