Hello, folks! In this article, we will discuss how to authenticate a Blazor WebAssembly (WASM) application with Azure AD (Active Directory) and its working principles. Blazor is an open-source framework for developing web apps using C# and HTML. Many modern web developers like to work with it because of its versatility.
Blazor WebAssembly uses open web standards to run and execute the .NET code directly in the browser sandbox using .NET runtime, which provides maximum execution speed on the client side. Securing our application from unauthorized access is a priority while handling our apps since authorization checks can be bypassed by modifying all the client-side code at the end-user level.
In this scenario, the best approach for securing single-page applications (SPA) is to perform authorization checks on the server side using any API endpoint based on the OAuth 2.0 protocol, such as OpenID Connect (OIDC) or Azure Active Directory (AAD).
Let’s discuss the step-by-step procedures to authenticate our Blazor WebAssembly applications with Azure AD (Active Directory).
In this blog, I have used Visual Studio 2019 to build an application. This software is required for you to follow along:
Follow these steps to create a Blazor WebAssembly hosted application:
The Blazor WebAssembly application will be created with three projects (client, server, and shared), as shown in the following screenshot.
Created sample demo
We have created the Blazor WebAssembly application. Now, let’s add the configuration to authenticate the Blazor WebAssembly app with AAD for a single organization, like for a work or school account.
First, we need to register our server API and client app in the Microsoft identity platform in the Azure portal to get the Application ClientID and tenantID and set the required configuration like redirect URL and other details.
Check out the register server API link and client app link for how to do this.
In this section, we are going to set up the authentication for calls to our APIs and its configurations.
using Microsoft.AspNetCore.Authentication.AzureAD.UI; using Microsoft.AspNetCore.Authentication; //… public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme) .AddAzureADBearer(options => Configuration.Bind("AzureAd", options)); //... } //… public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //... app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { //... }); }
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "{DOMAIN}", "TenantId": "{TENANT ID}", "ClientId": "{SERVER API APP CLIENT ID}", } }
using Microsoft.AspNetCore.Authorization; //… [Authorize] [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { //... }
In this section, we are going to set up the user authentication settings and UI configuration changes:
public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); //... builder.Services.AddHttpClient("BlazorWASMAuthApp.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)) .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>(); builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>() .CreateClient("BlazorWASMAuthApp.ServerAPI")); builder.Services.AddMsalAuthentication(options => { builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication); options.ProviderOptions.DefaultAccessTokenScopes.Add("{SCOPE URI}"); }); await builder.Build().RunAsync(); }
Replace {SCOPE URI} with your server client ID along with the scope name.
Check out this documentation for more details.
{ "AzureAd": { "Authority": "https://login.microsoftonline.com/{TENANT ID}", "ClientId": "{CLIENT APP CLIENT ID}", "ValidateAuthority": true } }
//... <script src="_content/Microsoft.Authentication.WebAssembly.Msal/AuthenticationService.js"></script> <script src="_framework/blazor.webassembly.js"></script>
@using System.Net.Http @using System.Net.Http.Json @using Microsoft.AspNetCore.Authorization @using Microsoft.AspNetCore.Components.Authorization //...
Almost done! We have finished the configuration changes. Let’s do the UI changes to complete it.
<CascadingAuthenticationState> <Router AppAssembly="@typeof(Program).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <NotAuthorized> <h1>Sorry!!</h1> <p> You are not authorized to access this page. Please log in. </p> </NotAuthorized> </AuthorizeRouteView> </Found> <NotFound> <LayoutView Layout="@typeof(MainLayout)"> <p>Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState>
@page "/counter" @attribute [Authorize] //…
@using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.WebAssembly.Authentication @inject NavigationManager Navigation @inject SignOutSessionStateManager SignOutManager <AuthorizeView> <Authorized> Hello, @context.User.Identity.Name! <button class="nav-link btn btn-link" @>Pages/Authentication.razor
@page "/authentication/{action}" @using Microsoft.AspNetCore.Components.WebAssembly.Authentication <RemoteAuthenticatorView Action="@Action" /> @code { [Parameter] public string Action { get; set; } }
//… <div class="top-row px-4"> <LoginDisplay /> <a href="http://blazor.net" target="_blank" class="ml-md-auto">About</a> </div> //…
Let’s run the app from the server project. You can see the demo of the runnable application in the GIF image.
You can download the complete source code of this example from this GitHub location.
In this blog post, we have learned how to secure a Blazor-WebAssembly-hosted application with Azure AD (Active Directory) authentication. In this way, you can secure your app with minimal lines of code.
Syncfusion provides more than 65 high-performance, lightweight, modular, and responsive Blazor UI controls such as DataGrid, Charts, and Scheduler to ease the work of developers. Check them out!
If you have any questions or feedback, please leave your valuable comments in the comments section below.
You can also contact us through our support forum, Direct-Trac, or feedback portal. We are always happy to assist you! Have a good day!