0
votes

I have set up authentication using Azure AD single tenet. Using applications roles for authorization.

The API is asp.net core 3.1 with a swagger client. All is tested and everything works. The Blazor client can login. But user.Identity has no role claims so AuthorizeView are not working.

So what am I missing? a nuget package or do I have to map the roles to a custom user account?

This is my jwt token with the 3 roles

{
"aud": "https://testacompany.onmicrosoft.com/customeredit-api",
"iss": "https://sts.windows.net/8506d453-347c-4239-adf7-602ca98f4853/",
"iat": 1614587145,
"nbf": 1614587145,
"exp": 1614591045,
"acr": "1",
"aio": "AUQAu/8TAAAAf2oBifx9vVtfPJXmlKP/MOzvpF3Flcnlt2BLFHe8B9K2NUFrQF4XP69vRu8voLMK5eo8zGgIl/aTdHOnrqmGaQ==",
"amr": [
    "pwd"
],
"appid": "1a454d3f-329b-490d-b0fe-521bf6f61478",
"appidacr": "0",
"email": "[email protected]",
"given_name": "Martin",
"idp": "https://sts.windows.net/3443ebe9-de49-471a-b7e5-9f9abfafac0c/",
"ipaddr": "131.165.55.123",
"name": "Martin Andersen",
"oid": "f121e73d-f5d8-436a-aef5-954cd286e80e",
"rh": "0.AAAAU9QGhXw0OUKt92AsqY9IUz9NRRqbMg1JsP5SG_b2FHiBAOY.",
"roles": [
    "EditCustomer",
    "EditAgreement",
    "Reader"
],
"scp": "Api.Access",
"sub": "oxMQxcyNNgU-fZMto4xwOOwrI18mlUgM1GyyNhAFmDQ",
"tid": "8506d453-347c-4239-adf7-602ca98f4853",
"unique_name": "[email protected]",
"uti": "K-zFcTY_mUG6RNzI-FdgAA",
"ver": "1.0"
}

In Blazor Program.cs

b.Services.AddMsalAuthentication<RemoteAuthenticationState, CustomUserAccount>(options =>
{
    options.UserOptions.RoleClaim = "role";
    b.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://testacompany.onmicrosoft.com/customeredit-api/Api.Access");
}).AddAccountClaimsPrincipalFactory<RemoteAuthenticationState,CustomUserAccount ,CustomUserFactory>();

b.Services.AddOptions();
b.Services.AddAuthorizationCore();

I also tried to create CustomUserFactory

public class CustomUserFactory : AccountClaimsPrincipalFactory<CustomUserAccount>
{
    public CustomUserFactory(IAccessTokenProviderAccessor accessor)
        : base(accessor)
    {
    }

    public override async ValueTask<ClaimsPrincipal> CreateUserAsync(
        CustomUserAccount account,
        RemoteAuthenticationUserOptions options)
    {
        var user = await base.CreateUserAsync(account, options);

        Console.WriteLine($"User IsAuthenticated: {user.Identity.IsAuthenticated}");
        
        if (user.Identity.IsAuthenticated)
        {
            var identity = (ClaimsIdentity)user.Identity;
            var roleClaims = identity.FindAll(identity.RoleClaimType).ToArray();
            if (roleClaims.Any())
            {
                foreach (var existingClaim in roleClaims)
                {
                    identity.RemoveClaim(existingClaim);
                }

                var rolesElem = account.AdditionalProperties[identity.RoleClaimType];

                if (rolesElem is JsonElement roles)
                {
                    Console.WriteLine($"JsonElement: {rolesElem}");
                    if (roles.ValueKind == JsonValueKind.Array)
                    {
                        
                        foreach (var role in roles.EnumerateArray())
                        {
                            Console.WriteLine($"role: {role.GetString()}");
                            identity.AddClaim(new Claim(options.RoleClaim, role.GetString()));
                        }
                    }
                    else
                    {
                        Console.WriteLine($"roles: {roles.GetString()}");
                        identity.AddClaim(new Claim(options.RoleClaim, roles.GetString()));
                    }
                }
            }
        }
        return user;
    }
}

But I think I need to parse the raw jwt and map the roles to my user. So how can I access the jwt token?

1
Are you already in the Azure portal granted the role to the logged-in user? - Carl Zhao
Users are in groups and application roles are connected to groups. The Swagger client works using roles - Martin Andersen
Yes I read it and tried "groupMembershipClaims": "All" and the custom profile. Ended up parsing the token and added the roles as claims - Martin Andersen
Looks like this issue has been resolved? Can you add an answer which can help people who may have the same issue? - Allen Wu

1 Answers

0
votes

This implementation should resolve your issue. I'm hoping it's included within future templates of .net 6+.

In Blazor Program.cs

builder.Services.AddMsalAuthentication<RemoteAuthenticationState, CustomUserAccount>
            (options =>
            {
                builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
                options.ProviderOptions.DefaultAccessTokenScopes.Add("https://testacompany.onmicrosoft.com/customeredit-api/Api.Access");
                options.UserOptions.RoleClaim = "role";
            }).AddAccountClaimsPrincipalFactory<RemoteAuthenticationState, CustomUserAccount, CustomUserFactory>();

Create a Custom User factory:

public class CustomUserFactory : AccountClaimsPrincipalFactory<CustomUserAccount>
{
    public CustomUserFactory(IAccessTokenProviderAccessor accessor)
        : base(accessor)
    {
     
    }

    public async override ValueTask<ClaimsPrincipal> CreateUserAsync(CustomUserAccount account, RemoteAuthenticationUserOptions options)
    {
        var initialUser = await base.CreateUserAsync(account, options);

        if (initialUser.Identity.IsAuthenticated)
        {
            var userIdentity = (ClaimsIdentity)initialUser.Identity;
            if (account?.Roles?.Length > 0)
            {
                foreach (var role in account?.Roles)
                {
                    userIdentity.AddClaim(new Claim("role", role));
                }
            }
            if (account?.Groups?.Length > 0)
            {
                foreach (var group in account?.Groups)
                {
                    userIdentity.AddClaim(new Claim("group", group));
                }
            }
        }

        return initialUser;
    }
}

Create the CustomUserAccount:

public class CustomUserAccount : RemoteUserAccount
{
    [JsonPropertyName("groups")]
    public string[] Groups { get; set; }

    [JsonPropertyName("roles")]
    public string[] Roles { get; set; }
}

The roles are now available via the AuthorizeView Component (on your page.razor):

 <AuthorizeView Roles="EditCustomer"> Content only available to EditCustomer Role</AuthorizeView>