|
| 1 | +--- |
| 2 | +title: Connect with Managed Identity using Azure AD in Azure Cosmos DB for PostgreSQL |
| 3 | +description: Learn how to connect and authenticate using Managed Identity when Azure AD authentication method is enabled on an Azure Cosmos DB for PostgreSQL cluster |
| 4 | +author: niklarin |
| 5 | +ms.author: nlarin |
| 6 | +ms.service: cosmos-db |
| 7 | +ms.subservice: postgresql |
| 8 | +ms.topic: how-to |
| 9 | +ms.date: 09/19/2023 |
| 10 | +--- |
| 11 | +# Connect with Managed Identity to Azure Cosmos DB for PostgreSQL |
| 12 | + |
| 13 | +[!INCLUDE [PostgreSQL](../includes/appliesto-postgresql.md)] |
| 14 | + |
| 15 | +> [!IMPORTANT] |
| 16 | +> Azure Active Directory authentication in Azure Cosmos DB for PostgreSQL is currently in preview. |
| 17 | +> This preview version is provided without a service level agreement, and it's not recommended |
| 18 | +> for production workloads. Certain features might not be supported or might have constrained |
| 19 | +> capabilities. |
| 20 | +> |
| 21 | +> You can see a complete list of other new features in [preview features](product-updates.md#features-in-preview). |
| 22 | +
|
| 23 | +You can use both system-assigned and user-assigned managed identities to authenticate to Azure Cosmos DB for PostgreSQL. This article shows you how to use a system-assigned managed identity for an Azure Virtual Machine (VM) to access an Azure Cosmos DB for PostgreSQL cluster. Managed Identities are automatically managed by Azure and enable you to authenticate to services that support Azure AD authentication without needing to insert credentials into your code. |
| 24 | + |
| 25 | +You learn how to: |
| 26 | +- Grant your VM access to an Azure Cosmos DB for PostgreSQL cluster |
| 27 | +- Create a user in the database that represents the VM's system-assigned identity |
| 28 | +- Get an access token using the VM identity and use it to query an Azure Cosmos DB for PostgreSQL cluster |
| 29 | +- Implement the token retrieval in a C# example application |
| 30 | + |
| 31 | +## Prerequisites |
| 32 | + |
| 33 | +- If you're not familiar with the managed identities for Azure resources feature, see this [overview](../../../articles/active-directory/managed-identities-azure-resources/overview.md). If you don't have an Azure account, [sign up for a free account](https://azure.microsoft.com/free/) before you continue. |
| 34 | +- To do the required resource creation and role management, your account needs "Owner" permissions at the appropriate scope (your Azure subscription or resource group). If you need assistance with a role assignment, see [Assign Azure roles to manage access to your Azure subscription resources](../../../articles/role-based-access-control/role-assignments-portal.md). |
| 35 | +- You need an Azure VM (for example, running Ubuntu Linux) that you'd like to use to access your database using Managed Identity |
| 36 | +- You need an Azure Cosmos DB for PostgreSQL cluster that has [Azure AD authentication method](./how-to-configure-authentication.md#choose-authentication-method) configured |
| 37 | +- To follow the C# example, first, complete the guide on how to [Connect with C#](./quickstart-app-stacks-csharp.md) |
| 38 | + |
| 39 | +## Create a system-assigned managed identity for your VM |
| 40 | + |
| 41 | +Use [az vm identity assign](/cli/azure/vm/identity/) with the `identity assign` command enables the system-assigned identity to an existing VM: |
| 42 | + |
| 43 | +```azurecli-interactive |
| 44 | +az vm identity assign -g myResourceGroup -n myVm |
| 45 | +``` |
| 46 | + |
| 47 | +Retrieve the application ID for the system-assigned managed identity, which you'll need in the next few steps: |
| 48 | + |
| 49 | +```azurecli |
| 50 | +# Get the client ID (application ID) of the system-assigned managed identity |
| 51 | +
|
| 52 | +az ad sp list --display-name vm-name --query [*].appId --out tsv |
| 53 | +``` |
| 54 | + |
| 55 | +## Create a PostgreSQL user for your Managed Identity |
| 56 | + |
| 57 | +Now, connect as the Azure AD administrator user to your Azure Cosmos DB for PostgreSQL cluster's coordinator, and run the following SQL statements, replacing `CLIENT_ID` with the client ID you retrieved for your system-assigned managed identity: |
| 58 | + |
| 59 | +```sql |
| 60 | +select * from pgaadauth_create_principal('<identity_name>', false, false); |
| 61 | +``` |
| 62 | + |
| 63 | +For more information on managing Azure AD enabled database roles, see [how to manage Azure AD enabled PostgreSQL roles](./how-to-configure-authentication.md#configure-azure-active-directory-authentication) |
| 64 | + |
| 65 | +The managed identity now has access when authenticating with the identity name as a role name and the Azure AD token as a password. |
| 66 | + |
| 67 | +## Retrieve the access token from the Azure Instance Metadata service |
| 68 | + |
| 69 | +Your application can now retrieve an access token from the Azure Instance Metadata service and use it for authenticating with the database. |
| 70 | + |
| 71 | +This token retrieval is done by making an HTTP request to `http://169.254.169.254/metadata/identity/oauth2/token` and passing the following parameters: |
| 72 | + |
| 73 | +* `api-version` = `2018-02-01` |
| 74 | +* `resource` = `https://ossrdbms-aad.database.windows.net` |
| 75 | +* `client_id` = `CLIENT_ID` (that you retrieved earlier) |
| 76 | + |
| 77 | +You get back a JSON result containing an `access_token` field - this long text value is the Managed Identity access token you should use as the password when connecting to the database. |
| 78 | + |
| 79 | +For testing purposes, you can run the following commands in your shell. |
| 80 | + |
| 81 | +> [!NOTE] |
| 82 | +> Note you need `curl`, `jq`, and the `psql` client installed. |
| 83 | +
|
| 84 | +```bash |
| 85 | +# Retrieve the access token |
| 86 | + |
| 87 | +export PGPASSWORD=`curl -s 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fossrdbms-aad.database.windows.net&client_id=CLIENT_ID' -H Metadata:true | jq -r .access_token` |
| 88 | + |
| 89 | +# Connect to the database |
| 90 | + |
| 91 | +psql "host=[FQDN_of_coordinator] port=5432 dbname=[db_name] user=citus sslmode=require" |
| 92 | +``` |
| 93 | + |
| 94 | +You're now connected to the cluster's coordinator. |
| 95 | + |
| 96 | +## Connect using Managed Identity in C# |
| 97 | + |
| 98 | +This section shows how to get an access token using the VM's user-assigned managed identity and use it to call Azure Cosmos DB for PostgreSQL. Azure Cosmos DB for PostgreSQL natively supports Azure AD authentication, so it can directly accept access tokens obtained using managed identities for Azure resources. When creating a connection to PostgreSQL, you pass the access token in the password field. |
| 99 | + |
| 100 | +Here's a .NET code example of opening a connection to PostgreSQL using an access token. This code must run on the VM to use the system-assigned managed identity to obtain an access token from Azure AD. Replace the values of HOST, USER, DATABASE, and CLIENT_ID. |
| 101 | + |
| 102 | +```csharp |
| 103 | +using System; |
| 104 | +using System.Net; |
| 105 | +using System.IO; |
| 106 | +using System.Collections; |
| 107 | +using System.Collections.Generic; |
| 108 | +using System.Text.Json; |
| 109 | +using System.Text.Json.Serialization; |
| 110 | +using Npgsql; |
| 111 | +using Azure.Identity; |
| 112 | + |
| 113 | +namespace Driver |
| 114 | +{ |
| 115 | + class Script |
| 116 | + { |
| 117 | + // Obtain connection string information from the portal for use in the following variables |
| 118 | + private static string Host = "[FQDN_of_coordinator]"; |
| 119 | + private static string User = "[NAME]"; |
| 120 | + private static string Database = "[DATABASE]"; |
| 121 | + |
| 122 | + static async Task Main(string[] args) |
| 123 | + { |
| 124 | + // |
| 125 | + // Get an access token for PostgreSQL. |
| 126 | + // |
| 127 | + Console.Out.WriteLine("Getting access token from Azure AD..."); |
| 128 | + |
| 129 | + // Azure AD resource ID for Azure Cosmos DB for PostgreSQL cluster is https://ossrdbms-aad.database.windows.net/ |
| 130 | + string accessToken = null; |
| 131 | + |
| 132 | + try |
| 133 | + { |
| 134 | + // Call managed identities for Azure resources endpoint. |
| 135 | + var sqlServerTokenProvider = new DefaultAzureCredential(); |
| 136 | + accessToken = (await sqlServerTokenProvider.GetTokenAsync( |
| 137 | + new Azure.Core.TokenRequestContext(scopes: new string[] { "https://ossrdbms-aad.database.windows.net/.default" }) { })).Token; |
| 138 | + |
| 139 | + } |
| 140 | + catch (Exception e) |
| 141 | + { |
| 142 | + Console.Out.WriteLine("{0} \n\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : "Acquire token failed"); |
| 143 | + System.Environment.Exit(1); |
| 144 | + } |
| 145 | + |
| 146 | + // |
| 147 | + // Open a connection to the PostgreSQL server using the access token. |
| 148 | + // |
| 149 | + string connString = |
| 150 | + String.Format( |
| 151 | + "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4}; SSLMode=Prefer", |
| 152 | + Host, |
| 153 | + User, |
| 154 | + Database, |
| 155 | + 5432, |
| 156 | + accessToken); |
| 157 | + |
| 158 | + using (var conn = new NpgsqlConnection(connString)) |
| 159 | + { |
| 160 | + Console.Out.WriteLine("Opening connection using access token..."); |
| 161 | + conn.Open(); |
| 162 | + |
| 163 | + using (var command = new NpgsqlCommand("SELECT version()", conn)) |
| 164 | + { |
| 165 | + |
| 166 | + var reader = command.ExecuteReader(); |
| 167 | + while (reader.Read()) |
| 168 | + { |
| 169 | + Console.WriteLine("\nConnected!\n\nPostgres version: {0}", reader.GetString(0)); |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + } |
| 175 | +} |
| 176 | +``` |
| 177 | + |
| 178 | +When run, this command gives an output like this: |
| 179 | + |
| 180 | +```output |
| 181 | +Getting access token from Azure AD... |
| 182 | +Opening connection using access token... |
| 183 | +
|
| 184 | +Connected! |
| 185 | +
|
| 186 | +Postgres version: PostgreSQL 16.0, compiled by Visual C++ build 1800, 64-bit |
| 187 | +``` |
| 188 | + |
| 189 | +## Next steps |
| 190 | +- Learn about [authentication in Azure Cosmos DB for PostgreSQL](./concepts-authentication.md). |
| 191 | +- Check out [Azure AD limits and limitations in Azure Cosmos DB for PostgreSQL](./reference-limits.md#azure-active-directory-authentication) |
| 192 | +- Learn how to configure authentication for Azure Cosmos DB for PostgreSQL clusters, see [Use Azure Active Directory and native PostgreSQL roles for authentication with Azure Cosmos DB for PostgreSQL](./how-to-configure-authentication.md). |
0 commit comments