Skip to content

Instantly share code, notes, and snippets.

@aidapsibr
Created February 14, 2021 00:21
Show Gist options
  • Save aidapsibr/3047df5f915c79600fcd2f60456b1585 to your computer and use it in GitHub Desktop.
Save aidapsibr/3047df5f915c79600fcd2f60456b1585 to your computer and use it in GitHub Desktop.
Demonstrates replacing the Managed Identity authentication strategy to do custom authentication such as Azure CLI login as a fall-back.
using Azure.Core;
using Azure.Identity;
using Microsoft.Data.SqlClient;
using System.Threading.Tasks;
namespace Example
{
public class AzureCredentialSqlAuthenticationProvider : SqlAuthenticationProvider
{
public async override Task<SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters)
{
var azureTokenCredential = new ChainedTokenCredential(
new ManagedIdentityCredential(parameters.UserId == string.Empty ? null : parameters.UserId),
new AzureCliCredential(),
new VisualStudioCodeCredential(),
new VisualStudioCredential());
var tokenResponse = await azureTokenCredential.GetTokenAsync(new TokenRequestContext(new[] { parameters.Resource }), cancellationToken: default);
return new SqlAuthenticationToken(tokenResponse.Token, tokenResponse.ExpiresOn);
}
public override bool IsSupported(SqlAuthenticationMethod authenticationMethod)
{
return authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryManagedIdentity
|| authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryMSI;
}
}
}
using Microsoft.Data.SqlClient;
namespace Example
{
/*
* Enable developer credential fall-back to support local developing
*
* https://github.com/dotnet/SqlClient/issues/815
* https://docs.microsoft.com/en-us/sql/connect/ado-net/introduction-microsoft-data-sqlclient-namespace?view=sql-server-ver15#azure-active-directory-managed-identity-authentication
*
* To use this authentication, just add this to your connection string instead of credentials
* Authentication=Active Directory Managed Identity; User Id={ObjectIdOfManagedIdentity};
*
* Requires Microsoft.Data.SqlClient >= 2.1.1
*/
var azureSqlTokenProvider = new AzureCredentialSqlAuthenticationProvider();
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity, azureSqlTokenProvider);
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryMSI, azureSqlTokenProvider);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment