This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Securing a Blazor WebAssembly Hosted Apps with Azure Active Directory – Part 2


Within the earlier article of this sequence, we’ve created a safe undertaking with Blazor WebAssembly Hosted and Azure Lively Listing.
On this article we’re going to add one other stage of safety: the roles.

Additionally on this case we are going to use a characteristic of Azure Lively Listing referred to as: “App Roles“.

So, let’s open our utility and make some modifications to it!

From the Azure Portal, come again to the App Registrations and seek for your two apps.

Image description

Open the app registration for the server app and underneath the “Handle” part of the left navigation pane, click on on “App roles“.

Image description

Click on on the button “Create app position” on the highest bar navigation and fill the shape with the details about the brand new position.

Image description

Take note of the sector “worth” as a result of it is going to be the worth that we’ll use in our code later.
It is reccomended to make use of lowcase letters.

Repeat these operations for different roles as: Viewer, PowerUser, and many others.

Now we have to do the identical steps for the consumer app.
Nevertheless it’s essential to make use of the identical values for this utility.
The sooner manner is to repeat the details about App roles immediately from the Manifest file and put them within the manifest of the consumer utility.

From the left navigation pane, click on on “Manifest“, choose the Json portion of the code about appRoles and replica it within the clipboard.

Image description

Now you’ll be able to open the manifest file of the consumer utility and replase the Json node with the brand new values.

That is it.

Navigate to the “Enterprise Functions and open the server app.

Image description

Below the menu “Handle” click on on “Customers and teams” after which “Add person/group“.

Image description

Within the new window, search and choose a person and the position that you just need to assign to him.

Image description

Now within the listing you’ll be able to see all of the customers with their position assigned.

Image description

Essential: repeat all these steps for the consumer utility.

Open the Shopper undertaking and add a category referred to as “SecureUserAccount” (however you’ll be able to select the identify that you just desire).
This class extends the RemoteUserAccount.

    public class SecureUserAccount : RemoteUserAccount
    {
        [JsonPropertyName("roles")]
        public string[] Roles { get; set; } = Array.Empty<string>();
    }
Enter fullscreen mode

Exit fullscreen mode

Now our utility have to know the right way to handle the roles from Azure AD.
To do this, we are able to create a brand new class within the consumer undertaking referred to as “SecureAccountFactory

    public class SecureAccountFactory : AccountClaimsPrincipalFactory<SecureUserAccount>
    {
        public SecureAccountFactory(IAccessTokenProviderAccessor accessor)
            : base(accessor)
        {
        }
        public async override ValueTask<ClaimsPrincipal> CreateUserAsync(SecureUserAccount account,
            RemoteAuthenticationUserOptions choices)
        {
            var initialUser = await base.CreateUserAsync(account, choices);
            if (initialUser.Id.IsAuthenticated)
            {
                var userIdentity = (ClaimsIdentity)initialUser.Id;
                foreach (var position in account.Roles)
                {
                    userIdentity.AddClaim(new Declare("appRole", position));
                }
            }
            return initialUser;
        }
    }
Enter fullscreen mode

Exit fullscreen mode

The final change within the consumer utility is within the Program.cs file.
Exchange the Msal authentication snippet with the brand new one:

builder.Providers.AddMsalAuthentication<RemoteAuthenticationState, SecureUserAccount>(choices =>
{
    builder.Configuration.Bind("AzureAd", choices.ProviderOptions.Authentication);
    choices.ProviderOptions.DefaultAccessTokenScopes.Add("api://957e1304-dd53-4589-b013-4a264dd19334/BlazorWASMHosted.API");
    choices.UserOptions.RoleClaim = "appRole";
})
.AddAccountClaimsPrincipalFactory<RemoteAuthenticationState, SecureUserAccount,
    SecureAccountFactory>();
Enter fullscreen mode

Exit fullscreen mode

Now it is time to change the server utility.

Open the Program.cs file and substitute the MsalAuthentication code with the brand new one:

builder.Providers.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(choices =>
        {
            builder.Configuration.Bind("AzureAd", choices);
            choices.TokenValidationParameters.RoleClaimType =
                "http://schemas.microsoft.com/ws/2008/06/id/claims/position";
        },
        choices => { builder.Configuration.Bind("AzureAd", choices); });
Enter fullscreen mode

Exit fullscreen mode

Let’s begin to work with the roles.

To start with, the server utility.
Prolong the Authorize attribute of the WeatherForecastController with the roles property:

[Authorize(Roles = "administrator")] 
Enter fullscreen mode

Exit fullscreen mode

Now solely a person with the Administrator position can name the controller.

Within the consumer app, open the Fetchdata.razor file and lengthen the identical attribute with the roles attributes:

@attribute [Authorize(Roles = "administrator")]
Enter fullscreen mode

Exit fullscreen mode



Show solely the hyperlinks in your position

If you wish to forestall {that a} person entry to a web page with the fallacious position, you’ll be able to disguise parts of the pages or hyperlinks within the utility.
You need to use one of many out-of-box options of Blazor referred to as “AuthorizeView“.

As an illustration, if you wish to disguise the web page Fetch knowledge, it is sufficient in case you add this code within the NavMenu.razor file.

<AuthorizeView Roles="administrator">
    <Approved>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch knowledge
            </NavLink>
        </li>
    </Approved>
</AuthorizeView>
Enter fullscreen mode

Exit fullscreen mode



Entry to the App Position from the code behind

It is very simple additionally to entry to the roles of the person from the code behind.
Fairly often inside an utility there lots of code that change the behaviour based mostly on the person permissions.

Let’s begin with a straightforward instance.
Open the Counter.razor web page and alter the code as beneath:

@code {
    [CascadingParameter]
    public Process<AuthenticationState> AuthState { get; set; }

    non-public int currentCount = 0;

    non-public async Process IncrementCount()
    {
        var authState = await AuthState;
        var person = authState.Person;

        if (person.IsInRole("viewer"))
        {
            currentCount += 2;
        }

        if (person.IsInRole("administrator"))
        {
            currentCount -= 2;
        }
    }
}
Enter fullscreen mode

Exit fullscreen mode

Now you know the way to create a brand new app on Azure Portal, assign roles to it and work with the roles in your Blazor purposes.

You’ll find the supply code of the instance on GitHub.
Observe the directions within the Readme file.

Thanks and drop me a remark you probably have questions or feedbacks!

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?