iTranslated by AI
Considerations for Connecting to SQL Database with Managed Identity in Avanade Beef
Introduction
Avanade Beef (hereinafter referred to as "Beef") is an automated generation tool for Web APIs based on ASP.NET Core.
For an overview, please refer to the following slides.
Problem
Incidents involving data leaks due to accidentally exposing SQL Database connection strings in source control occur frequently. One way to prevent this is to use Managed Identity. By using an ID (service principal) tied to an Azure resource instead of a username and password, you can access SQL Database in a passwordless manner.
The steps are available in the following tutorial:
You change the connection string to the following:
Server=tcp:<server-name>.database.windows.net;Authentication=Active Directory Default; Database=<database-name>;
You enable the Managed Identity in App Service and grant permissions to that Managed Identity.
CREATE USER [<identity-name>] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [<identity-name>];
ALTER ROLE db_datawriter ADD MEMBER [<identity-name>];
ALTER ROLE db_ddladmin ADD MEMBER [<identity-name>];
GO
However, even if you follow these steps, you will encounter a 500 error when using Beef.
Solution
This is because Beef uses several stored procedures (even if you are using the configuration with Entity Framework). You usually don't need to be aware of them because they are automatically generated when you run dotnet run database in your Database project, but the following stored procedures exist:
The tutorial mentioned above assigns the db_datareader, db_datawriter, and db_ddladmin roles to the Managed Identity. However, these roles do not allow the execution of stored procedures, resulting in an error. To prevent this, you need to assign the db_owner role or define a custom role.
CREATE ROLE db_executor
GRANT EXECUTE TO db_executor
ALTER ROLE db_executor ADD MEMBER [<identity-name>];
Conclusion
In reality, this issue can occur even without using Managed Identity, but please be aware that it often occurs specifically when following tutorials for enabling Managed Identity.
Discussion