0

I have Blazor server based app. I basically show database columns for admins in app. The auth is done using Azure AD, in startup.cs i have added

options.AddPolicy("AppAdmins", policy => policy.RequireRole("Admin", "SuperAdmin", "Owner"));

In Main page i have

<AuthorizeView Policy="AppAdmins">
    <Authorized>
        @Body
    </Authorized>
    <NotAuthorized>
        You are not authorized to use this application.
    </NotAuthorized>
</AuthorizeView>

This works, now for specific role users, i need to show db columns specific to role. How do i access roles in Index.razor or Index.razor.cs to filter the fields?

I'm new to Blazor and .Net Core.

prvn
  • 406
  • 3
  • 7
  • 24
  • If anyone stuck with this scenario, you can check https://stackoverflow.com/a/59784095/1820783. It took me 2 days just to figure out how it's done, all the forum articles i had to go through, man Microsoft docs is vast. – prvn Nov 02 '20 at 15:29

1 Answers1

1

You can inject the AuthenticationStateProvider in your component, gets the user, checks if he's authenticated, and then retrieves the roles assigned to him.

@using System.Security.Claims
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider


 var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            var identity = (ClaimsIdentity)user.Identity;
            var roleClaims = identity.FindAll(identity.RoleClaimType);

           foreach (var existingClaim in roleClaims)
           {
             // Do something with the roles...
            }
        }
        else
        {
           // "The user is NOT authenticated.";
        }
enet
  • 41,195
  • 5
  • 76
  • 113