Skip to content

Fix Auth0 Role Extraction#110

Merged
mpaulosky merged 3 commits intomainfrom
feature/auth0-role-improvements
Mar 12, 2026
Merged

Fix Auth0 Role Extraction#110
mpaulosky merged 3 commits intomainfrom
feature/auth0-role-improvements

Conversation

@mpaulosky
Copy link
Owner

Summary

Fixes admin users not seeing admin-only menu items despite having the Admin role in Auth0.

Changes

  • Enhanced Auth0AuthenticationStateProvider to handle multiple role formats:
    • Comma-separated strings
    • JSON arrays
    • Single role values
  • Added debug logging for authentication and role extraction
  • Updated auth0-setup.md with:
    • Post-Login Action configuration
    • Role creation and assignment steps
    • Troubleshooting guide
  • Added 13 unit tests for Auth0AuthenticationStateProvider

Testing

  • All 82 Web.Tests.Unit tests pass
  • All 206 Web.Tests.Bunit tests pass
  • All 11 Architecture.Tests pass

Closes #107

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mpaulosky mpaulosky added squad Squad triage inbox — Lead will assign to a member squad:gandalf Assigned to Gandalf (Security Officer) labels Mar 12, 2026
Copilot AI review requested due to automatic review settings March 12, 2026 05:22
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes role extraction in the Web UI’s Auth0 authentication state provider so admin users reliably receive ClaimTypes.Role claims (and therefore see admin-only navigation) when Auth0 emits roles in different formats.

Changes:

  • Updated Auth0AuthenticationStateProvider to extract roles from a custom namespaced claim (comma-separated, JSON array, or single value) and from standard "roles" claims.
  • Added unit tests covering multiple role formats, whitespace/duplicates, and error scenarios.
  • Expanded docs/auth0-setup.md with role setup, Post-Login Action configuration, and troubleshooting steps.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
src/Web/Services/Auth0AuthenticationStateProvider.cs Adds multi-format role extraction + additional logging around claims/roles.
tests/Web.Tests.Unit/Services/Auth0AuthenticationStateProviderTests.cs New unit test coverage for role parsing and edge cases.
tests/Web.Tests.Unit/GlobalUsings.cs Adds Microsoft.Extensions.Logging for the new tests.
docs/auth0-setup.md Documents Auth0 roles + Post-Login Action setup and troubleshooting.

You can also share your feedback on Copilot code review. Take the survey.

Comment on lines +156 to +162
private static void AddRoleIfNotExists(ClaimsIdentity identity, string role)
{
string trimmedRole = role.Trim();
if (!string.IsNullOrEmpty(trimmedRole) && !identity.HasClaim(ClaimTypes.Role, trimmedRole))
{
identity.AddClaim(new Claim(ClaimTypes.Role, trimmedRole));
}
Copy link

Copilot AI Mar 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AddRoleIfNotExists assumes role is non-null and calls Trim(). When roles are sourced from JsonSerializer.Deserialize<string[]>(...), the array can contain null elements (e.g., ["Admin", null]), which would cause a NullReferenceException during role extraction. Consider treating roles as string? and skipping null/whitespace entries before trimming/adding.

Copilot uses AI. Check for mistakes.
Comment on lines +68 to +72
_logger.LogInformation("User roles extracted: {Roles}", string.Join(", ", finalRoles));
}
else
{
_logger.LogWarning("No roles found for authenticated user. Check Auth0 Post-Login Action configuration.");
Copy link

Copilot AI Mar 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GetAuthenticationStateAsync is called frequently in a Blazor app; logging at Information/Warning on every call (especially the "No roles found" warning) can create significant log noise and may page on normal scenarios (users without roles, misconfigured dev environments). Consider downgrading these to Debug/Trace, or only warning when a roles claim is present but cannot be parsed / is unexpectedly empty.

Suggested change
_logger.LogInformation("User roles extracted: {Roles}", string.Join(", ", finalRoles));
}
else
{
_logger.LogWarning("No roles found for authenticated user. Check Auth0 Post-Login Action configuration.");
_logger.LogDebug("User roles extracted: {Roles}", string.Join(", ", finalRoles));
}
else
{
_logger.LogDebug("No roles found for authenticated user. Check Auth0 Post-Login Action configuration.");

Copilot uses AI. Check for mistakes.
var result = await _sut.GetAuthenticationStateAsync();

// Assert
result.User.Identity!.IsAuthenticated.Should().BeTrue();
Copy link

Copilot AI Mar 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test claims invalid JSON is handled gracefully, but it doesn't assert the expected outcome (e.g., that no role claims were added). Adding an assertion that ClaimTypes.Role claims are empty would better lock in the behavior and catch regressions.

Suggested change
result.User.Identity!.IsAuthenticated.Should().BeTrue();
result.User.Identity!.IsAuthenticated.Should().BeTrue();
result.User.Claims.Where(c => c.Type == ClaimTypes.Role).Should().BeEmpty();

Copilot uses AI. Check for mistakes.
@github-actions
Copy link

github-actions bot commented Mar 12, 2026

Test Results Summary

  7 files  ± 0   38 suites  ±0   14s ⏱️ -1s
853 tests +13  853 ✅ +13  0 💤 ±0  0 ❌ ±0 
864 runs  +13  864 ✅ +13  0 💤 ±0  0 ❌ ±0 

Results for commit c95a0f1. ± Comparison against base commit dfcc460.

♻️ This comment has been updated with latest results.

@codecov
Copy link

codecov bot commented Mar 12, 2026

Codecov Report

❌ Patch coverage is 70.24793% with 36 lines in your changes missing coverage. Please review.
✅ Project coverage is 55.52%. Comparing base (dfcc460) to head (c95a0f1).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/Web/Extensions/AuthExtensions.cs 59.49% 12 Missing and 20 partials ⚠️
...c/Web/Services/Auth0AuthenticationStateProvider.cs 95.00% 1 Missing and 1 partial ⚠️
src/Web/Components/Layout/NavMenu.razor 0.00% 0 Missing and 1 partial ⚠️
src/Web/Program.cs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #110      +/-   ##
==========================================
+ Coverage   54.10%   55.52%   +1.41%     
==========================================
  Files         124      124              
  Lines        2717     2826     +109     
  Branches      287      313      +26     
==========================================
+ Hits         1470     1569      +99     
+ Misses       1032     1027       -5     
- Partials      215      230      +15     
Files with missing lines Coverage Δ
src/Web/Components/User/Profile.razor 0.00% <ø> (ø)
src/Web/Components/Layout/NavMenu.razor 0.00% <0.00%> (ø)
src/Web/Program.cs 0.00% <0.00%> (ø)
...c/Web/Services/Auth0AuthenticationStateProvider.cs 94.54% <95.00%> (+94.54%) ⬆️
src/Web/Extensions/AuthExtensions.cs 65.59% <59.49%> (-34.41%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Scribe and others added 2 commits March 11, 2026 22:32
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Address reviewer feedback from PR #110:
  - Handle null elements in deserialized role arrays (null safety)
  - Downgrade role logging from Info/Warning to Debug (reduce log noise)
  - Add assertion for empty roles on invalid JSON in test
- Fix OnTokenValidated event to extract roles from custom namespace claim
- Update NavMenu to link profile page from greeting
- Clean up Profile page layout and move to /user/profile

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mpaulosky mpaulosky merged commit 6dcdcbf into main Mar 12, 2026
25 checks passed
@mpaulosky mpaulosky deleted the feature/auth0-role-improvements branch March 12, 2026 06:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

squad:gandalf Assigned to Gandalf (Security Officer) squad Squad triage inbox — Lead will assign to a member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Sprint 1] Fix Auth0 Role Extraction

2 participants