Service-to-Service comminucation with Refit & Client Credentials Flow for Entra ID
For a recent project I needed my ASP.NET Core backend service to talk to an external license server using the Entra ID Client Credentials Flow for authentication. For these scenarios I like using Refit to generate the required http client logic. And adding auth for Entra ID is pretty straight forward as well if you know which libraries to use.
Here’s what we want to do:
create a Refit Interface for the API we need to call
create a provider to automatically get the required Access Token on every API call
configure Refit with our auth provider in ASP.NET Core Dependency Injection
For the authentication we’ll be using the Microsoft Authentication Library (MSAL) for .NET aka the Microsoft.Identity.Client NuGet package. The library will handle token caching & refreshing on it’s own so we have just a few lines of code.
Let’s look at the files:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The LicenseAuthProdivder will create an IConfidentialClientApplication with either ClientSecret or Certificate depending on your needs (see commented out code).
The GetToken() method will be called by Refit whenever an API call is made.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
To access the license server we need to provide the following options with either ClientSecret or CertificatePath configured.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
And to bring everything together we configure Refit to use the LicenseAuthProvider before registering it for Dependency Injection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters