Thursday, July 18, 2024

Setting Up and Configuring Authentication and Authorization in Blazor WASM with .NET API Backend on Azure

Blazor WebAssembly (WASM) is a powerful framework for building interactive client-side web apps with .NET. In this post, we’ll explore how to set up and configure authentication and authorization in a Blazor WASM application with a .NET API backend on Azure.

1. Setting Up the Blazor WASM Application

First, let’s create a new Blazor WASM application. You can do this using the .NET CLI:

dotnet new blazorwasm -n MyBlazorApp -au Individual

The -au Individual flag sets up the application to use individual user accounts, which is necessary for authentication.

2. Configuring Azure AD Authentication

Next, we need to configure Azure Active Directory (AD) for authentication. Here’s how to do it:

  1. In the Azure portal, create a new App Registration.
  2. Set the Redirect URI to the address of your Blazor app (e.g., https://localhost:5001/authentication/login-callback).
  3. Note down the Application (client) ID and Directory (tenant) ID.

Then, in the appsettings.json file of your Blazor app, add the following:

{
  "AzureAd": {
    "Authority": "https://login.microsoftonline.com/{Directory (tenant) ID}",
    "ClientId": "{Application (client) ID}",
    "ValidateAuthority": true
  }
}

3. Setting Up the .NET API Backend

Now, let’s set up the .NET API backend. You can create a new Web API project using the .NET CLI:

dotnet new webapi -n MyApi

4. Configuring Azure AD Authentication in the API

In the API project, install the Microsoft.Identity.Web NuGet package. Then, in the Startup.cs file, add the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
}

And in the appsettings.json file, add the following:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "{Your Azure AD domain}",
    "TenantId": "{Directory (tenant) ID}",
    "ClientId": "{Application (client) ID}"
  }
}

5. Configuring Authorization

Finally, let’s configure authorization. In the Startup.cs file of your API project, add the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorization(options =>
    {
        options.AddPolicy("ApiAccess", policy =>
            policy.RequireClaim("http://schemas.microsoft.com/identity/claims/scope", "Api.Access"));
    });
}

And in your controllers, use the [Authorize] attribute to enforce the policy:

[Authorize(Policy = "ApiAccess")]
public class MyController : ControllerBase
{
    // Controller methods here
}

That’s it! You’ve now set up and configured authentication and authorization in a Blazor WASM application with a .NET API backend on Azure. Happy coding!