A Blazor Server application making requests to a secured Web API.

Praveen Desai
Version 1
Published in
4 min readSep 21, 2023

We have a need to make calls to a secured web API from a Blazor Server application that is authenticated using Azure AD.

Photo by Justin Morgan on Unsplash

We will discuss below topics,

  • Creating Blazor Server App with Azure AD Authentication enabled.
  • Setting up the Client(Blazor UI) to make Protected web APIs.
  • How to make protected web APIs call ?

Like web apps, ASP.NET and ASP.NET Core web APIs are protected with authentication and authorisation because their controller actions are prefixed with the [Authorize] attribute. The controller actions can be called only if the API is called with an authorized identity. By following the steps outlined below, we can meet this specific requirement.

  1. Set up Azure AD authentication for your Blazor Server app.
    a) Create an Azure AD application registration for your Blazor Server app in the Azure portal.
    b) Configure the required permissions and API access for the application registration.
    c) Note down the “Application ID” and “Directory (tenant) ID” of the application registration.
  2. Configure Azure AD authentication in your Blazor Server app.
    a) Open the appsettings.json file in your Blazor Server app.
    b) Add the following configuration settings:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "yourtenant.onmicrosoft.com",
"TenantId": "your-tenant-id",
"ClientId": "your-client-id",
"CallbackPath": "/signin-oidc"
"ClientSecret":
}

Replace the yourtenant.onmicrosoft.com with your Azure AD tenant domain, and replace your-tenant-id ,your-client-id and ClientSecret with the respective IDs from the Azure AD application registration.

3. Install the required NuGet packages:
Microsoft recommends that we use the Microsoft.Identity.Web NuGet package when developing an ASP.NET Core-protected API calling downstream web APIs.

4. Configure authentication services in Program.cs:
In the ConfigureServices method, add the following code to configure Azure AD authentication and set up for calling Downstream web API.

// …
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi()
.AddDownstreamApi("MyApi", builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
// …

a) Blazor Server application needs to acquire a token for downstream API. EnableTokenAcquisitionToCallDownstreamApi() method exposes the ITokenAcquistion service that will be used in pages.

b) DownStreamApi is a section in appSettings.json file as

"DownstreamApi": {
"BaseUrl": "https://{{ypu-web-api}}.azurewebsites.net",
"Scopes": "{{define your scope here}}"//api://{{Clientid}}/access_users
},

c) AddInMemoryTokenCaches() allows the token to be cached in memory.

d) If the web app needs to call another API resource, repeat the .AddDownstreamApi() method with the relevant scope.

e) The following image shows the possibilities of Microsoft.Identity.Web and impact on Program.cs:

Image from Microsoft Docs -https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-web-api-call-api-app-configuration?tabs=aspnetcore
Image from Microsoft Docs -https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-web-api-call-api-app-configuration?tabs=aspnetcore

After we build a client application object, use it to acquire a token that you can use to call a web API.

5. Blazor UI that calls Web APIs:

Microsoft.Identity.Web adds extension methods that provide convenience services for calling Microsoft Graph or downstream web API.

  • Option 1: Call Microsoft Graph with the SDK
  • Option 2: Call a downstream web API with the helper class
  • Option 3: Call a downstream web API without the helper class

We use the helper class approach to acquire tokens using the ITokenAcquisition service and you use the token to make protected calls to web APIs.


public HTTPRequestHelper(IHttpClientFactory httpClientFactory, ITokenAcquisition tokenAquisitionService,
IConfiguration configuration, ILogger<HTTPRequestHelper> logger
)
{
_httpClientFactory = httpClientFactory;
_tokenAquisitionService = tokenAquisitionService;
_configuration = configuration;
_logger = logger;
}

// Method to acquire
public async Task<string> GetAccessTokenAsync()
{
var scopes = new[] { _configuration["DownstreamApi:scopes"] };
var token = await _tokenAquisitionService.GetAccessTokenForUserAsync(scopes);
return token;
}

Having obtained the token, we will utilize it for making HTTP calls as demonstrated below.

public async Task<Type> GetAsync<Type>(string namedHttpClient, string requestUrl)
{
_logger.LogInformation("Starting - GetAsync method in HttpRequestHelper");
HttpResponseMessage response;

var _httpClient = _httpClientFactory.CreateClient(namedHttpClient);
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", await GetAccessTokenAsync());

// Call the web API.
response = await _httpClient.GetAsync(requestUrl);

// return from method.
}

The bearer token that’s set in the header holds information about the app identity as well as about the user information necessary for authorizing web API requests.

I trust that the steps provided made it straightforward to configure the Blazor Server App for making secure web API calls. These same steps can be applied to other client applications as well.

Happy Coding:)

Resources :

About the author:

Praveen Desai is a .Net Developer here at Version 1.

--

--