Home General
Options

Can we get an option configure Azure SQL credential options in the connection properties?

Right now I have to do this:

void Main()
{

var dbContext = GetTokenizedDbContext();

to use queries against my DbContext class because the MacOS azure credential stack from Microsoft.SqlClient is not working. It hangs up trying to go through the various prioritized options for authenticating against Azure.

So the implementation of the above that works for me is:

public PopStoreContext GetTokenizedDbContext()
{
Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ":/opt/homebrew/bin");

// Configure Azure credential options
var options = new DefaultAzureCredentialOptions
{
    ExcludeEnvironmentCredential = true,
    ExcludeManagedIdentityCredential = true,
    ExcludeSharedTokenCacheCredential = true,
    ExcludeVisualStudioCredential = true,
    ExcludeAzureDeveloperCliCredential = true,
    ExcludeAzurePowerShellCredential = true,
    ExcludeInteractiveBrowserCredential = true, // Exclude interactive browser if it’s causing issues on macOS
    TenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID") // Ensure AZURE_TENANT_ID is set in your environment
};

var credential = new DefaultAzureCredential(options);

// Get token for Azure SQL Database
var tokenRequestContext = new TokenRequestContext(new[] { "https://database.windows.net//.default" });
var token = credential.GetToken(tokenRequestContext);
Console.WriteLine("Token acquired successfully. Expires on: " + token.ExpiresOn);

// Azure SQL connection string (without credentials, as token will be used)
string connectionString = "Data Source=AAAAAAA.database.windows.net;Initial Catalog=BBBBBBB;Encrypt=true;app=LINQPad;MultipleActiveResultSets=true";

// Create a new SqlConnection with the token
var connection = new SqlConnection(connectionString);

connection.AccessToken = token.Token;

    // Initialize your DbContext with the connection
var dbContextOptions = new DbContextOptionsBuilder<PopStoreContext>()
    .UseSqlServer(connection)
    .Options;

var dbContext = new PopStoreContext(dbContextOptions);
return dbContext;

}

I really wish I could put the DefaultCredentialOptions in the connection properties dialog so I didn't have to scaffold every linqpad query using Azure SQL with the above code.

Sign In or Register to comment.