Connecting to Fabric using SqlClient

Microsoft Fabric doesnt yet support SqlLogins, but you can still connect programatically by using the Azure.Identity Classes which support both Managed Identity (if run from somewhere supporting that), or Visual Studio authentication if in debug or unit test mode. The examples below are c#, but similar works in Python too.

Below is a code sample with a full example console App in GitHub

There are two cautions here if developing a production application

  1. Azure.Identity currently always tries Managed Identity First and then other methods and this timeout process can take up to 5 seconds, so best to have a way to set which authentication method you want.
  2. The Access Token from AAD is valid for about an hour and can take a second or so to request, so best to cache this if you can and check the ExpiresOn property for when it needs a fresh token.

Good Luck 😉

using System.Data.SqlClient;
using Azure.Identity;
using Azure.Core;
using System.Data;

var  DefaultAzureCredentialOptions  =  new DefaultAzureCredentialOptions 
        ExcludeAzureCliCredential = true,
        ExcludeManagedIdentityCredential = true,
        ExcludeSharedTokenCacheCredential = true,
        ExcludeVisualStudioCredential = false,
        ExcludeAzurePowerShellCredential = true,
        ExcludeEnvironmentCredential = true,
        ExcludeVisualStudioCodeCredential = true,
        ExcludeInteractiveBrowserCredential = true

    var accessToken = new DefaultAzureCredential(DefaultAzureCredentialOptions).GetToken(new TokenRequestContext(new string[] { "" }));
    var sqlServer = "";
    var sqlDatabase = "";
    var connectionString = $"Server={sqlServer};Database={sqlDatabase}";

    //Set AAD Access Token, Open Conneciton, Run Queries and Disconnect
    using var con = new SqlConnection(connectionString);
    con.AccessToken = accessToken.Token;
    using var cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT @@Version";
    var res =cmd.ExecuteScalar();


Leave a Reply