Skip to content

Instantly share code, notes, and snippets.

@your-azure-coach
Last active July 10, 2023 14:06
Show Gist options
  • Select an option

  • Save your-azure-coach/907471dc7fe67b04bd338275c908469f to your computer and use it in GitHub Desktop.

Select an option

Save your-azure-coach/907471dc7fe67b04bd338275c908469f to your computer and use it in GitHub Desktop.
Managed Identity code snippets
using Azure.Storage.Blobs; //v12.4.3
var blobClient = new BlobClient(
new Uri($”https://{_storageAccountName}.blob.core.windows.net/{_blobContainerName}/msi-{Guid.NewGuid()}.txt”),
credential
);
var testFileStream = File.OpenRead(_testFilePath);
await blobClient.UploadAsync(testFileStream, true);
testFileStream.Close();
using Azure.Identity; //v1.2.0-preview.4
var credential = new ChainedTokenCredential(
new ManagedIdentityCredential(),
new AzureCliCredential()
);
using Azure.Identity; //v1.2.0-preview.4
var credential = new DefaultAzureCredential();
using Azure.Identity; //v1.2.0-preview.4
var options = new DefaultAzureCredentialOptions
{
ExcludeEnvironmentCredential = true,
ExcludeManagedIdentityCredential = false,
ExcludeSharedTokenCacheCredential = true,
ExcludeVisualStudioCredential = true,
ExcludeVisualStudioCodeCredential = true,
ExcludeAzureCliCredential = false,
ExcludeInteractiveBrowserCredential = true
};
var credential = new DefaultAzureCredential(options);
using Azure.Security.KeyVault.Secrets; //v4.0.3
var secretClient = new SecretClient(
new Uri($"https://{_keyVaultName}.vault.azure.net/"),
credential
);
var secret = await secretClient.GetSecretAsync("Test");
using Azure.Messaging.ServiceBus; //v7.0.0-preview.4
var serviceBusClient = new ServiceBusClient(
$"{_serviceBusName}.servicebus.windows.net",
credential
);
var queueSendClient = serviceBusClient.CreateSender(_queueName);
var message = new ServiceBusMessage(File.ReadAllText(_testFilePath));
await queueSendClient.SendMessageAsync(message);
using System.Data.SqlClient; //v4.8.1
var accessToken = credential.GetToken(new TokenRequestContext(new[] { "https://database.windows.net/.default"})).Token;
using (var sqlConnection = new SqlConnection($"Server=tcp:{_sqlServerName},1433;Database={_sqlDatabaseName}"))
{
sqlConnection.AccessToken = accessToken
using (var sqlCommand = new SqlCommand())
{
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.CommandText = "INSERT INTO dbo.Tests VALUES(@Input)";
sqlCommand.Parameters.AddWithValue("@Input", File.ReadAllText(_testFilePath));
sqlCommand.Connection = sqlConnection;
sqlConnection.Open();
await sqlCommand.ExecuteNonQueryAsync();
}
}
@michalkrzych

Copy link
Copy Markdown

These days you can use Microsoft.Data.SqlClient (im using Version="5.1.1") to access an Azure SQL Db using Managed Identity:

// Build the connection string
var connectionStringBuilder = new SqlConnectionStringBuilder
{
    DataSource = "tcp:<sqlservername>.database.windows.net", // replace with your azure sql db server name
    InitialCatalog = "<databasename>", // replace with your azure sql db name
    Authentication = SqlAuthenticationMethod.ActiveDirectoryDefault,
    ConnectTimeout = 30,
    Encrypt = true,
    TrustServerCertificate = true
};

using (SqlConnection connection = new SqlConnection(connectionStringBuilder.ConnectionString))
{
    try
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand( "SELECT TOP(1000) * FROM dbo.<tableName>", connection))
        {
            command.ExecuteNonQuery();
        }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment