Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.