How do I implement Office 365 authentication in Blazor WebAssembly?

When using Blazor WebAssembly to enforce Office 365 authentication, it is necessary to include the tenant ID and client ID in the appsettings.json file, which can be found under your Azure account. In Azure AD, a tenant is a dedicated Azure service instance that a company receives and owns after signing up for a Microsoft cloud service such as Azure or Microsoft 365. Each tenant ID is distinct and separate from other tenants. Procedure outline Create a new environment in Power Apps and note the web API service root URL. Register your Azure account. Create a WebAssembly app using Azure AD for authentication. Update the callback URL in the app to run the app. Grant API permissions to access data from the dataverse and modify the code to display the data in the app. Please refer to this link for a detailed explanation of the implementation of Office 365 authentication.

How do I intercept routing in Blazor before it navigates?

The routing interception concept is sometimes used to restrict user access to some page or link if they did some work or made some changes on a specific page. In the following code, you can use the NavigateTo() method to intercept routing inside the If condition. The routing happens according to the values passed in the condition. Create the class file [RouteData.cs]. …………………. .. namespace BlazorApp.Data { public class RouteData { public string Textfield { get; set; } } } To register the RouteData class as a scoped service in Program.cs, you can use the following code snippet. [Program.cs] builder.Services.AddScoped<BlazorServerApp.Data.RouteData>(); Add the following code to the [Index.razor] page. @page "/" @inject Data.RouteData RouteData <p>Type the text below to allow Home page intercepting</p> <textarea @bind="RouteData.Textfield"></textarea> Check the condition and allow the navigation process in the [NavMenu.razor] page as shown. @inject NavigationManager NavigationManager @inject {Your App name}.Data.RouteData RouteData <div class="@NavMenuCssClass" @onclick="ToggleNavMenu"> <ul class="nav flex-column"> <li class="nav-item px-3"> <NavLink class="nav-link" @onclick="Navigate" Match="NavLinkMatch.All"> <span class="oi oi-home" aria-hidden="true"></span> Home </NavLink> </li> ……………………. . . </ul> </div> @code { private bool collapseNavMenu = true; private string NavMenuCssClass => collapseNavMenu ? "collapse" : null; private void ToggleNavMenu() { collapseNavMenu = !collapseNavMenu; } private void Navigate() { if (RouteData.Textfield == null) NavigationManager.NavigateTo(""); } ………………… . . . Output Home page routing is intercepted when you type text in the text area. When the text area value is null, the app navigates to the home page. View Sample in GitHub

How do I detect navigation events in Blazor WebAssembly?

We can use NavigationManager, which has a built-in LocationChanged event that will be triggered when the user navigates away from the current page. In the following code, we use an alert JS function by adding the IJSRuntime to show the user has navigated by overriding the OnInitialized() method through the alert message. [Index.razor] When the user navigates from the home page to the counter page or vice versa, the alert message stating “User has navigated to other page” will be shown. View Sample in GitHub

How do I allow anonymous users on a specific Blazor page?

We generally use authentication for specific pages to prevent access by unauthorized users. In the case that we do want a specific page to be accessed by any users, not only authorized users, we will use the anonymous users category. To make a Blazor page accessible by all users, use [AllowAnonymous] with @attribute code in the _Imports.razor file in your app. [_Imports.razor] By doing this users can access the secured page (here we secured the fetch data) without a login.

How do I implement Windows authentication and authorization in Blazor WebAssembly?

As the Blazor client runs in the browser, both user authorization and authentication for WebAssembly will be completely handled by the back-end API. The back-end web API must handle the authorization on every API call, and it tells the Blazor app whether the user is authenticated and has resource access. It enables your Blazor app to show the correct context to the user. Create a Blazor WebAssembly app using Visual Studio 2019 with ASP.NET Core hosting enabled. Reorganize the folder names according to usage: Sample.Server is renamed to Sample.Api as we are going to use this as our API. Sample.Client is renamed to Sample.WebApp. Sample.Shared is renamed to Sample.Common. In the Sample.Common folder, create a Models folder, and move the generated WeatherForecast class to this folder and change its namespace to Sample.Models. Add the AuthorizedUser class in the Models folder under the Sample.Shared folder. namespace Sample.Common { public class AuthorizedUser { public string Name { get; set; } public string Roles { get; set; } } Add a new SettingsController file in the Sample.Api folder. using Sample.Models; using Microsoft.AspNetCore.Mvc; namespace Sample.Api.Controllers { [Route("api/[controller]")] [ApiController] public class SettingsController : ControllerBase { [HttpGet("user")] public AuthorizedUser GetUser() { return new AuthorizedUser(); // User signed in: //return new AuthorizedUser { Name = "UserName" }; } } } Prepare your Sample.WebApp Install the NuGet package Microsoft.AspNetCore.Components.Authorization. Add the installed package in the _Imports.razor file. Wrap the <CascadingAuthenticationState> in the App.razor file. <CascadingAuthenticationState> <Router AppAssembly="@typeof(Program).Assembly"> ... </Router> </CascadingAuthenticationState> Add a Service folder and add a ClientAuthorizationService class in it. using Sample.Models; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; namespace Sample.WebApp.Services { public class ClientAuthorizationService : AuthenticationStateProvider { private const string AuthenticationType = "BackEnd"; private readonly HttpClient _httpClient; public ClientAuthorizationService(HttpClient httpClient) { if (httpClient == null) throw new ArgumentNullException(nameof(httpClient)); _httpClient = httpClient; } public string ApiUriGetAuthorizedUser { get; set; } public string ApiUriSignIn { get; set; } public string ApiUriSignOut { get; set; } public AuthorizedUser AuthorizedUser { get; private set; } = new AuthorizedUser(); public override async Task<AuthenticationState> GetAuthenticationStateAsync() { ClaimsPrincipal user; if (!string.IsNullOrEmpty(ApiUriGetAuthorizedUser)) AuthorizedUser = await _httpClient.GetJsonAsync<AuthorizedUser>(ApiUriGetAuthorizedUser); if (string.IsNullOrEmpty(AuthorizedUser.Name)) { user = new ClaimsPrincipal(); } else { var identity = new ClaimsIdentity(CreateClaims(AuthorizedUser), AuthenticationType); user = new ClaimsPrincipal(identity); } return new AuthenticationState(user); } private static IEnumerable<Claim> CreateClaims(AuthorizedUser authorizedUser) { yield return new Claim(ClaimTypes.Name, authorizedUser.Name); var roles = authorizedUser.Roles?.Split(',') ?? new string[0]; foreach (var role in roles) yield return new Claim(ClaimTypes.Role,role.Trim()); } } } Add the following code in the Program.cs file. using Microsoft.AspNetCore.Components.Authorization; using System.Net.Http; ... public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.Services.AddAuthorizationCore(); builder.Services.AddScoped<ClientAuthorizationService>(CreateAuthorizationService); builder.Services.AddScoped<AuthenticationStateProvider>(sp => sp.GetRequiredService<ClientAuthorizationService>()); builder.Services.AddOptions(); ... private static ClientAuthorizationService CreateAuthorizationService(IServiceProvider serviceProvider){ var httpClient = serviceProvider.GetRequiredService<HttpClient>(); var service = new ClientAuthorizationService(httpClient) { ApiUriGetAuthorizedUser = "api/settings/user", ApiUriSignIn = "AzureADB2C/Account/SignIn", ApiUriSignOut = "AzureADB2C/Account/SignOut", }; return service; } Create a new Razor component SignInDisplay.razor in the shared folder. @using Sample.WebApp.Services @inject ClientAuthorizationService AuthorizationService <AuthorizeView> <Authorized> <div> <span class="form-control">@AuthorizationService.AuthorizedUser.Name</span> </div> <div> <a class="btn btn-outline-primary" href="@AuthorizationService.ApiUriSignOut">Sign Out</a> </div> </Authorized> <NotAuthorized> <div> <a class="btn btn-outline-primary" href="@AuthorizationService.ApiUriSignIn">Sign In</a> </div> </NotAuthorized> </AuthorizeView> In the Shared/MainLayout page, add the following code. <div class="top-row px-4 auth"> <SignInDisplay /> </div> Run the app with Sample.Api as the startup file and see the output as follows. Since Windows authorization is not yet implemented in the API, If you click the Sign In button, you will be rerouted to a page stating, “Sorry, there’s nothing at this address.” When you change the code in the GetUser() method in the SettingsController to include the name of the user, the app will be shown as follows. Refer to this link for more information.