Hello!
If you are tired of my .NET MAUI articles, let's talk about .NET Aspire and authentication in your distributed applications.
If you don't know, .NET Aspire is an opinionated, cloud-ready stack for building observable, production-ready, distributed applications. It is designed to improve the experience of building .NET cloud-native apps. Learn more about .NET Aspire here.
But what task am I trying to solve and what problems am I having?
I have a default .NET Aspire app with a Blazor frontend and API service. The user should be able to sign in on UI using Microsoft Entra ID (Azure Active Directory) and call the API service. Unfortunately, the API request from the Blazor frontend to API Service returns 401/unauthenticated.
The issue is rather common (there are multiple issues opened on GitHub) and I spent about 1 week to make a successful response from the API Service. So let's go with what you need to make it work.
If you don't have an Azure Active Directory, watch this video on how to set it up:
And Azure Active Directory (B2C):
API Service
Starting with a configuration of API Service:
Create a new .NET Aspire project.
Install the
Microsoft.Identity.Web
package in the API project.Update
appsettings.json
with your AAD configuration:
Then modify
Program.cs
with the registration of WebApi Authentication:
Update your endpoints with
[Authorize]
attribute or call.RequireAuthorization()
for minimal API.
API Service is ready.
FrontEnd
Install the next packages in a Web project:
Update
appsettings.json
with your AAD configuration:
IMPORTANT. Pay attention to scopes. It is required for the Downstream API. If you forget to change the Scopes to an array, when you try to use the IDownstreamApi the scopes will appear null, and IDownstreamApi will attempt an anonymous (unauthenticated) call to the downstream API, which will result in a 401/unauthenticated.
Update
Program.cs
to register required services:
Downstream API
Downstream API is an HTTP Wrapper, that under the hood retrieves the token and then makes the request.
MicrosoftIdentityConsentAndConditionalAccessHandler
is a handler for Blazor-specific APIs to handle incremental consent and conditional access.
We are done. Start the application and check the result.
The full code can be found on GitHub.