randy
randy

Reputation: 275

AAD to Sql Server - DefaultAzureCredential in IIS

what is the trick to use your AAD credentials using Azure.Identity and Sql Server when using IIS?

Ultimately i want to use User Assigned Managed Identity with Sql Server, but i also need to debug locally.

This code works locally and in Azure when running in a console app.

var credential = new DefaultAzureCredential();
var token = credential.GetToken(
    new Azure.Core.TokenRequestContext(
        new[] { "https://database.windows.net/.default" }
));

connection.AccessToken = token.Token;

However, when i run my web app, which is a .net core 3.1 web app, i get the following exception.

I do have the Tools > Azure Service Authentication set up for my AAD user. My AAD user does have access to the database. The above code works in my console app. I'm suing EFCore 3.1. That code is in the ctor of the dbcontext. I also got it to work in the https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi sample using IIS express. I'm not sure if the issue is IIS express vs IIS or if it has to do with my startup.cs. i've tried az login and that didn't help either. I've tried running my IIS app pool with local system or my account with no difference.

Here is the exception message i get from the web app.

DefaultAzureCredential failed to retrieve a token from the included credentials.

Upvotes: 1

Views: 2590

Answers (1)

randy
randy

Reputation: 275

I figured it out. This page describes the steps. https://learn.microsoft.com/en-us/dotnet/api/overview/azure/service-to-service-authentication#cant-retrieve-tokens-when-debugging-app-in-iis

In addition to those steps i had the added complexity that my AD account is [email protected] but my same account in AAD is [email protected]. So i had to switch my App Pool settings to [email protected].

Upvotes: 2

Related Questions