Hi [@Anish Reghunandanan]
Even though you've tagged Static Web Apps, Tutorial: Connect to Azure databases from App Service without secrets using a managed identity is still applicable; so you can leverage those instructions.
You can assign a System Managed identity to your static web app and then add that add that identity as a user to your Azure SQL database per the following command:
CREATE USER [<app-name>] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [<app-name>];
ALTER ROLE db_datawriter ADD MEMBER [<app-name>];
ALTER ROLE db_ddladmin ADD MEMBER [<app-name>];
GO
Once you've added the identity to your SQL instance, you add the connection string Server=tcp:<server-name>.database.windows.net;Database=<database-name>;TrustServerCertificate=True
as an application setting and retrieve inside your application code. You also need to add Azure.Identity package to your application so that you can use DefaultAzureCredential
. This code will leverage the identity of the application to retrieve token which is used to access the database.
You can utilize the access token returned by DefaultAzureCredential
on the SqlConnection
object as follows:
var conn = (System.Data.SqlClient.SqlConnection)Database.Connection;
var credential = new Azure.Identity.DefaultAzureCredential();
var token = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://database.windows.net/.default" }));
conn.AccessToken = token.Token;