How to create a connection string using App Registration/Service Principal for an ASP.NET Core Web API with EF Core and SQL Server using Microsoft Entra MFA
I have an ASP.NET Core Web API that uses Entity Framework Core to connect to a SQL Server instance with Microsoft Entra MFA authentication.
Currently, I can connect locally using this connection string:
Server=tcp:some-server.database.windows.net,1433;Authentication=Active Directory Interactive;Database=some-database;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
However, this approach opens a browser prompt for password entry each time, which won’t work in a deployed environment like App Service or a container.
I need to implement a solution using a service principal with a secret token. I’ve already generated the following credentials:
- Service Principal Name
- Secret
- Application (Client) ID
- Tenant ID
- Subscription ID
- Object ID
- Directory ID
What is the proper connection string format for this scenario, and what additional steps are required to properly deploy the application?
To create a connection string using App Registration/Service Principal for your ASP.NET Core Web API with EF Core and SQL Server using Microsoft Entra MFA, you need to use the Active Directory Service Principal authentication mode with your client ID and secret. The proper connection string format is Server=tcp:your-server.database.windows.net,1433;Initial Catalog=your-database;Authentication=Active Directory Service Principal;User Id=your-client-id;Password=your-client-secret;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;, along with configuring your app settings and securing the credentials in production environments.
Contents
- Understanding Microsoft Entra Authentication Methods
- Creating the Proper Connection String
- Configuring ASP.NET Core Web API
- Security Best Practices
- Deployment Considerations
- Troubleshooting Common Issues
Understanding Microsoft Entra Authentication Methods
Microsoft Entra (formerly Azure Active Directory) supports several authentication modes for SQL Server connections, each suited for different scenarios:
- Active Directory Interactive - Opens a browser prompt for user authentication (what you’re currently using locally)
- Active Directory Service Principal - Uses a service principal’s client ID and secret for programmatic authentication
- Active Directory Managed Identity - Uses the application’s managed identity (ideal for Azure-hosted applications)
- Active Directory Integrated - Uses Windows authentication
- Active Directory Password - Uses username and password
For your deployed application scenario, Active Directory Service Principal is the appropriate choice as it doesn’t require user interaction and can be automated using your service principal credentials.
According to the Microsoft documentation, the Active Directory Service Principal authentication mode is specifically designed for applications that need to authenticate as a service principal, making it perfect for your ASP.NET Core Web API deployment.
Creating the Proper Connection String
Based on your credentials and the research findings, here’s the proper connection string format for your service principal:
Server=tcp:your-server.database.windows.net,1433;
Initial Catalog=your-database;
Authentication=Active Directory Service Principal;
User Id=your-client-id;
Password=your-client-secret;
Encrypt=True;
TrustServerCertificate=False;
Connection Timeout=30;
Key components explained:
Server=tcp:your-server.database.windows.net,1433- Your SQL Server endpointInitial Catalog=your-database- Your database nameAuthentication=Active Directory Service Principal- Specifies service principal authenticationUser Id=your-client-id- Your application (client) ID from Entra registrationPassword=your-client-secret- Your service principal secret
From the Stack Overflow discussion, this format is confirmed to work with .NET applications, though you’ll need to ensure your service principal has the appropriate SQL Server permissions.
Configuring ASP.NET Core Web API
1. App Settings Configuration
Add your connection string to appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=tcp:your-server.database.windows.net,1433;Initial Catalog=your-database;Authentication=Active Directory Service Principal;User Id=your-client-id;Password=your-client-secret;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
},
"AzureAd": {
"ClientId": "your-client-id",
"ClientSecret": "your-client-secret",
"TenantId": "your-tenant-id"
}
}
2. DbContext Configuration
Configure your DbContext to use the connection string:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Your entity configurations
}
}
// In Startup.cs or Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
3. Secure Configuration in Production
In production, never store secrets directly in configuration files. Instead:
Option A: Use Azure App Configuration
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(builder.Configuration["AppConfig:ConnectionString"])
.ConfigureRefresh(refresh =>
{
refresh.Register("ConnectionStrings:DefaultConnection", refreshAll: true);
});
});
Option B: Use Azure Key Vault
As mentioned in the research findings from WebNetHelper, you can access Azure SQL connection strings from Azure Key Vault:
builder.Configuration.AddAzureKeyVault(
new Uri(builder.Configuration["KeyVault:Endpoint"]),
new DefaultAzureCredential());
Security Best Practices
-
Never commit secrets to source control - Use Azure Key Vault or App Configuration for production secrets
-
Use managed identities in Azure - For Azure-hosted applications, consider using managed identity instead of service principals for better security:
csharp// Connection string for managed identity Server=tcp:your-server.database.windows.net,1433; Initial Catalog=your-database; Authentication=Active Directory Managed Identity; Encrypt=True; TrustServerCertificate=False; Connection Timeout=30; -
Implement proper credential rotation - Regularly rotate your service principal secrets
-
Use environment-specific configurations - Have different settings for development, staging, and production
-
Secure your DbContext - Ensure your DbContext is properly configured to use secure connection handling
Deployment Considerations
Azure App Service Deployment
When deploying to Azure App Service:
-
Configure App Settings in the Azure portal:
- Add
ConnectionStrings:DefaultConnectionwith your service principal connection string - Or use managed identity configuration
- Add
-
Set Environment Variables for sensitive data:
AzureAd:ClientIdAzureAd:ClientSecretAzureAd:TenantId
-
Enable Managed Identity (recommended):
powershellaz webapp identity assign --resource-group your-resource-group --name your-app-name
As mentioned in the Microsoft Learn tutorial, this approach generates a passwordless connection string that your app can use.
Container Deployment
For containerized deployments:
- Use Azure Key Vault to inject secrets into containers
- Configure connection strings via environment variables
- Implement health checks to verify database connectivity
Troubleshooting Common Issues
1. “Login failed for user” errors
This typically occurs when:
- Service principal doesn’t have SQL Server permissions
- Incorrect connection string format
- Expired or invalid credentials
Solution: Verify your service principal has been granted access to the SQL database:
CREATE USER [your-client-id] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [your-client-id];
ALTER ROLE db_datawriter ADD MEMBER [your-client-id];
2. “Cannot set the AccessToken property if ‘Authentication’ has been specified”
As seen in the Stack Overflow discussion, this error occurs when mixing authentication methods. Ensure you’re using either:
- Connection string with authentication parameters, OR
- Programmatic token setting without authentication in the connection string
3. Certificate validation issues
If you encounter SSL certificate errors, ensure:
Encrypt=Trueis setTrustServerCertificate=Falsefor production- Proper certificate chain validation
4. Performance optimization
Consider these performance improvements:
- Use connection pooling
- Configure appropriate timeout values
- Implement retry policies for transient failures
Conclusion
To successfully implement service principal authentication for your ASP.NET Core Web API with SQL Server:
- Use the correct connection string format with
Authentication=Active Directory Service Principal - Properly configure your service principal with the necessary SQL Server permissions
- Implement secure credential management using Azure Key Vault or managed identities
- Configure your ASP.NET Core application to use the connection string properly
- Test thoroughly in both development and production environments
For optimal security in Azure deployments, consider migrating to managed identity authentication as recommended in the Microsoft documentation, which eliminates the need to store secrets and provides better security posture for cloud-native applications.
Sources
- Microsoft Learn - Connect to Azure SQL with Microsoft Entra authentication and SqlClient
- Stack Overflow - How do I create connection string with App Registration/Service Principal for a Web API using EF Core app with SQL Server using Microsoft Entra MFA
- Microsoft Learn - Securely connect .NET apps to Azure SQL Database using Managed Identity
- Microsoft Learn - Deploy ASP.NET Core and Azure SQL Database app
- WebNetHelper - Accessing Azure SQL Connection String from Azure Key Vault in ASP.NET Core API
- Stack Overflow - What SQL Server connection string works with .NET Framework 4.5 in Microsoft Entra ID?