'Authenticating on behalf of a user from durable functions using MSAL
We have a suite of dotnet 6 azure functions (v4) which serve data to an single page client application.
The client authenticates with our api on behalf of the signed in user. These endpoints go on to call a downstream dependency also on behalf of the user using the Microsoft.Identity.Web library and a distributed sql token cache.
In addition to these apis, we have a durable function, which is triggered by one of our api functions. The resulting orchestrator spins up to process a queue of imports, which can take up to 30 minutes to process. These imports also require interaction with a downstream api on behalf of the user who kicked off the durable function.
The issue I'm facing presently is how to fetch a bearer token for these downstream outbound requests once the durable function takes over.
FYI, the outgoing http requests requiring on-behalf-of authentication are a few layers of abstraction away from the orchestrator (i.e. ochestrator => activity function => service => client). We're not using DurableHttpRequest for these requests.
Any help with this would be greatly appreciated!
Solution 1:[1]
I've since found this sample in the azure samples github repo:
https://github.com/Azure-Samples/ms-identity-dotnet-advanced-token-cache
Essentially, it involves writing a cache adapter using MsalDistributedTokenCacheAdapter (included in the Identity.Web library) to intercept writes to the token cache, in order to store data about the MsalAccount associated with the token. You can then use a User Principal Name to rehydrate the MsalAccount in an http-less context and pass that account into AcquireTokenSilent to refresh your token. The examples have the Api and background service in separate projects (the latter is a console app), but I've managed to get it working within the same project.
There are too many moving parts to share code in this answer, but the sample does hold the solution.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | finbag |
