Download API call using Incremental Consent fails

Travis Hall 0 Reputation points
2025-08-25T06:11:53.44+00:00

We are calling an API from a Blazor app. (.NET 8, Microsoft.NET.Sql.Web, Blazor Server)

The API is called via a client class generated by NSwag from an Open API spec file; therefore, we use .EnableTokenAcquisitionToCallDownstreamApi to modify the HTTP request as it is sent, to add authentication data.

The API call is wrapped in a try/catch, so that we can use ConsentHandler.HandleException to redirect to a login page if the authentication token is not available.

During development on our local machines, this works fine, but we rarely, if ever, call ConsentHandler.HandleException. The environment ensures that we are logged in, and attempt to secure an access token generally succeeds (unless we have done something to make the cached credentials invalid).

However, when deployed into Azure, the application calls the API, the call throws an exception (of type MsalUiRequiredException). The ConsentHandler handles this exception by redirecting to a login page, which may required to the user to log in, then redirects back to the Blazor page, which calls the API again. Again, the API throws an MsalUiRequiredException, the ConsentHandler redirects to login, the login redirects straight back to the application (because by now the user is definitely logged in - after the first login page redirection, if not before), and we loop like this until the browser refuses to call the pages any more.

During startup, AddMicrosoftIdentityWebAuthentiation, EnableTokenAcquisitionToCallDownstreamApi, AddMicrosoftIdentityUI, AddAuthorization, AddMicrosoftIdentityConsentHandler, UseAuthentication, UseAuthorization, and MapBlazorHub are all being called, in the correct order as far as we can tell. (Missing some parts of this seems to be the common reason that a redirect loop like this occurs.)

We are also able to call the API successfully (using different endpoints from the one that is currently causing us the most problems) but only as long as we store the response to the API call using PersistentComponentState. This is only a workaround for some cases, because the results of some of our API calls are too large to store in PersistentComponentState. However, it does tell us that our API can be called correctly in some circumstances. We do not know why this fixes the problem in these cases. When this workaround is in use, we do see the redirection to the login page occur, but only once, with the API call being successfully after being redirected back  to the Blazor page. If the page is refreshed, it will go through the redirection again, but only for that one loop.

Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.