Search code examples
c#blazorasp.net-core-identity

How to set/find user roles from Organization based Identity in .NET core


I'm trying to find out what role(s) a user has within a Blazor Server app that has Authentication setup for an organization that uses MS accounts and Azure Active Directory. I would imagine that the roles are set by the IT Operations team managing the MS accounts, but I'm not finding where to verify that at.

So I would like to know: where are roles set when using Org authentication, how can I change them, and is there a simple way to see what roles an authenticated user has?

I tried looking for an authenticated user's role in the MS doc example code using the cascade parameter like below:

@page "/"

<button @onclick="LogUsername">Log username</button>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        LogUsername();
    }

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            var test = user.Claims.Where(c => c.Type.Contains("Role")); // also tried "role"
            string role = test.FirstOrDefault().ToString();
            Console.WriteLine($"{role} is authenticated.");
        }
        else
        {
            Console.WriteLine("The user is NOT authenticated.");
        }
    }
}

Identity has a RoleClaimType but I can't find anything else that would tell what the Role for a given user is. Am I looking in the wrong spot for this maybe? I couldn't find any detailed docs on how Organiztion Authentication works with Identity in .NET core and Blazor, so any tips, advice, or nudges in the right direction is appreciated!


Solution

  • Roles are set in the azure portal. Azure Active Directory -> App Registrations -> [your app] -> Roles and Administrators. For custom roles, your organization will need Azure AD Premium P1 or P2 licenses.

    As for how to retrieve them, here is a quote from documentation:

    Get role claims. When a user signs in, the application receives the user's assigned role(s) in a claim with type http://schemas.microsoft.com/ws/2008/06/identity/claims/role (the roles claim in a JWT token).

    A user can be assigned multiple roles, or no role. In your authorization code, don't assume the user has exactly one role claim. Instead, write code that checks whether a particular claim value is present:

    if (context.User.HasClaim(ClaimTypes.Role, "Admin")) { ... }