Skip to content

Latest commit

 

History

History
47 lines (36 loc) · 1.91 KB

azure-postgresql-ef-client.md

File metadata and controls

47 lines (36 loc) · 1.91 KB

Add Azure authenticated Npgsql client

By default, when you call AddAzurePostgresFlexibleServer in your PostgreSQL hosting integration, it configures 📦 Azure.Identity NuGet package to enable authentication:

dotnet add package Azure.Identity
<PackageReference Include="Azure.Identity"
                  Version="*" />

The PostgreSQL connection can be consumed using the client integration and Azure.Identity:

builder.AddNpgsqlDbContext<YourDbContext>(
    "postgresdb", 
    configureDataSourceBuilder: (dataSourceBuilder) =>
{
    if (!string.IsNullOrEmpty(dataSourceBuilder.ConnectionStringBuilder.Password))
    {
        return;
    }

    dataSourceBuilder.UsePeriodicPasswordProvider(async (_, ct) =>
    {
        var credentials = new DefaultAzureCredential();
        var token = await credentials.GetTokenAsync(
            new TokenRequestContext([
                "https://ossrdbms-aad.database.windows.net/.default"
            ]), ct);

        return token.Token;
    },
    TimeSpan.FromHours(24),
    TimeSpan.FromSeconds(10));
});

The preceding code snippet demonstrates how to use the xref:Azure.Identity.DefaultAzureCredential class from the xref:Azure.Identity package to authenticate with Microsoft Entra ID and retrieve a token to connect to the PostgreSQL database. The UsePeriodicPasswordProvider method is used to provide the token to the connection string builder.