Share Authentication Session across ASP.NET Core Microservices with AzureAd

Lili Xu
2 min readMay 4, 2021

This post is mainly about a practical example on configuring shared authentication session and the on-behalf-of (OBO) flow across multiple ASP.NET Core services.

In this example the application contains three microservices.

  1. WebApp service for client main interaction.
  2. WebAPI service serves client operational requests.
  3. Background Data Processing Service does data processing job with user delegated permission.

All Services’ Startup.cs

Register Microsoft Identity WebApp with AzureAd Configuration Section, Enable OBO flow and distributed token cache. Register a cosmosDBCache implementation below as well.

Then, configure data protection to share the same symmetric key accross services for encryption/decryption of the auth cookie. In this example it use a blob account to save the key. The background worker does not need the data protection part, as it does not take request from client directly.

WebAPI Controller

As the client request is made to controller on authentication, user consent is checked first in AuthorizeForScopes Attributes before service making the OBO token request. Otherwise the service redirects user to AAD for consent.

The default ITokenAcquisition implementation could be DI into the controller and build a TokenAcqusitionTokenCredential class for BlobServiceClient. During token acquisition, it firstly acquires user identity from HttpContext, checks token cache and makes token request to AAD.

Background Data Worker

Different with WebAPI, there’s no HttpContext for the default TokenAcqusition to get user identity and inform MSAL to perform OBO flow. So that background worker requires the WebAPI to provide the userId & tenantId info in RPC call.

TokenCredentialWithCache implementation leverages IMSALTokenCacheProvider (which was DI from DistributedTokenCache registration) and IAccount is the key for retrieving token in cache, with the default cache serialization implementation of the Microsoft.Identity.Web, IAccount.AccountId is {userId}.{tenantId}.

So far, configuration has been successfully made to share authentication session across microservices. Each service can leverage the token cache and make OBO token request. With default “offline_access” scope requested in OpenIdConnect, the OBO flow could be performed even when the user login session is inactive.

--

--