Home > front end >  Authenticating a Blazor WebAssembly app with Azure Active Directory
Authenticating a Blazor WebAssembly app with Azure Active Directory

Time:01-26

I've already got an existing Blazor WebAssembly app and I'm attempting to add authentication with Azure Active Directory.

I've added the Microsoft.Authentication.WebAssembly.Msal nuget.

In my server's Program.cs, I've added the following code:

builder.Services.AddMsalAuthentication(options =>
        {
            builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
            options.ProviderOptions.LoginMode = "redirect";
        });

And I've added the following to my appsettings.json

  "AzureAd": {
    "Instance": "xxxxxxxxxxx",
    "Domain": "xxxxxxxxxxx",
    "TenantId": "xxxxxxxxxxx",
    "ClientId": "xxxxxxxxxxx",
    "CallbackPath": "xxxxxxxxxxx"
  },

I'm struggling to understand what else I need to add so that when I run the app, I get the Microsoft sign in screen.

CodePudding user response:

You need to require authorization for parts of the application, or for the entire app. By default, all routes inside the application are open to the public. If you want to shield any of these routes, you need to explicitly ask for authorization.
How to do this is documented here: enter image description here

You need to add 3 parts, authentication injection in Program.cs, configurations in appsettings.json, and the module for sign view, 2 of them you already had, and the left is the sign in/out button in the top navigation bar, so that you can click it to redirect to Microsoft sign in page. You can create the template project and copy the razor components into your project.

LoginDisplay.razor:

@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  @onclick="BeginLogout">Log out</button>
    </Authorized>
    <NotAuthorized>
        <a href="authentication/login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

@code{
    private async Task BeginLogout(MouseEventArgs args)
    {
        await SignOutManager.SetSignOutState();
        Navigation.NavigateTo("authentication/logout");
    }
}
  • Related