Skip to content

Commit ef77b53

Browse files
authored
Update howto-connect-with-managed-identity.md
Updating the doc to use system-assigned managed identity and the MSAL library.
1 parent d61fb68 commit ef77b53

File tree

1 file changed

+20
-40
lines changed

1 file changed

+20
-40
lines changed

articles/postgresql/howto-connect-with-managed-identity.md

Lines changed: 20 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@ ms.custom: devx-track-csharp, devx-track-azurecli
1111

1212
# Connect with Managed Identity to Azure Database for PostgreSQL
1313

14-
This article shows you how to use a user-assigned identity for an Azure Virtual Machine (VM) to access an Azure Database for PostgreSQL server. Managed Service 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.
14+
You can use both system-assigned and user-assigned managed identities to authenticate to Azure Database for PostgreSQL. This article shows you how to use a system-assigned managed identity for an Azure Virtual Machine (VM) to access an Azure Database for PostgreSQL server. 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.
1515

1616
You learn how to:
1717
- Grant your VM access to an Azure Database for PostgreSQL server
18-
- Create a user in the database that represents the VM's user-assigned identity
18+
- Create a user in the database that represents the VM's system-assigned identity
1919
- Get an access token using the VM identity and use it to query an Azure Database for PostgreSQL server
2020
- Implement the token retrieval in a C# example application
2121

@@ -27,39 +27,24 @@ You learn how to:
2727
- You need an Azure Database for PostgreSQL database server that has [Azure AD authentication](howto-configure-sign-in-aad-authentication.md) configured
2828
- To follow the C# example, first complete the guide how to [Connect with C#](connect-csharp.md)
2929

30-
## Creating a user-assigned managed identity for your VM
30+
## Creating a system-assigned managed identity for your VM
3131

32-
Create an identity in your subscription using the [az identity create](/cli/azure/identity#az_identity_create) command. You can use the same resource group that your virtual machine runs in, or a different one.
32+
Use [az vm identity assign](/cli/azure/vm/identity/) with the `identity assign` command enable the system-assigned identity to an existing VM:
3333

3434
```azurecli-interactive
35-
az identity create --resource-group myResourceGroup --name myManagedIdentity
35+
az vm identity assign -g myResourceGroup -n myVm
3636
```
3737

38-
To configure the identity in the following steps, use the [az identity show](/cli/azure/identity#az_identity_show) command to store the identity's resource ID and client ID in variables.
38+
Retrieve the application ID for the system-assigned managed identity, which you'll need in the next few steps:
3939

4040
```azurecli
41-
# Get resource ID of the user-assigned identity
42-
resourceID=$(az identity show --resource-group myResourceGroup --name myManagedIdentity --query id --output tsv)
43-
44-
# Get client ID of the user-assigned identity
45-
clientID=$(az identity show --resource-group myResourceGroup --name myManagedIdentity --query clientId --output tsv)
46-
```
47-
48-
We can now assign the user-assigned identity to the VM with the [az vm identity assign](/cli/azure/vm/identity#az_vm_identity_assign) command:
49-
50-
```azurecli
51-
az vm identity assign --resource-group myResourceGroup --name myVM --identities $resourceID
52-
```
53-
54-
To finish setup, show the value of the Client ID, which you'll need in the next few steps:
55-
56-
```bash
57-
echo $clientID
41+
# Get the client ID (application ID) of the system-assigned managed identity
42+
az ad sp list --display-name obs-locdev-wus2 --query [*].appId --out tsv
5843
```
5944

6045
## Creating a PostgreSQL user for your Managed Identity
6146

62-
Now, connect as the Azure AD administrator user to your PostgreSQL database, and run the following SQL statements:
47+
Now, connect as the Azure AD administrator user to your PostgreSQL database, and run the following SQL statements, replacing `CLIENT_ID` with the client ID you retrieved for your system-assigned managed identity:
6348

6449
```sql
6550
SET aad_validate_oids_in_tenant = off;
@@ -96,7 +81,7 @@ You are now connected to the database you've configured earlier.
9681

9782
This section shows how to get an access token using the VM's user-assigned managed identity and use it to call Azure Database for PostgreSQL. Azure Database 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.
9883

99-
Here's a .NET code example of opening a connection to PostgreSQL using an access token. This code must run on the VM to access the VM's user-assigned managed identity's endpoint. .NET Framework 4.6 or higher or .NET Core 2.2 or higher is required to use the access token method. Replace the values of HOST, USER, DATABASE, and CLIENT_ID.
84+
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.
10085

10186
```csharp
10287
using System;
@@ -107,6 +92,7 @@ using System.Collections.Generic;
10792
using System.Text.Json;
10893
using System.Text.Json.Serialization;
10994
using Npgsql;
95+
using Azure.Identity;
11096

11197
namespace Driver
11298
{
@@ -117,31 +103,25 @@ namespace Driver
117103
private static string Host = "HOST";
118104
private static string User = "USER";
119105
private static string Database = "DATABASE";
120-
private static string ClientId = "CLIENT_ID";
106+
//private static string ClientId = "CLIENT_ID";
121107
122-
static void Main(string[] args)
108+
static async Task Main(string[] args)
123109
{
124110
//
125111
// Get an access token for PostgreSQL.
126112
//
127-
Console.Out.WriteLine("Getting access token from Azure Instance Metadata service...");
113+
Console.Out.WriteLine("Getting access token from Azure AD...");
128114

129115
// Azure AD resource ID for Azure Database for PostgreSQL is https://ossrdbms-aad.database.windows.net/
130-
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("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=" + ClientId);
131-
request.Headers["Metadata"] = "true";
132-
request.Method = "GET";
133116
string accessToken = null;
134117

135118
try
136119
{
137120
// Call managed identities for Azure resources endpoint.
138-
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
121+
var sqlServerTokenProvider = new DefaultAzureCredential();
122+
accessToken = (await sqlServerTokenProvider.GetTokenAsync(
123+
new Azure.Core.TokenRequestContext(scopes: new string[] { "https://ossrdbms-aad.database.windows.net/.default" }) { })).Token;
139124

140-
// Pipe response Stream to a StreamReader and extract access token.
141-
StreamReader streamResponse = new StreamReader(response.GetResponseStream());
142-
string stringResponse = streamResponse.ReadToEnd();
143-
var list = JsonSerializer.Deserialize<Dictionary<string, string>>(stringResponse);
144-
accessToken = list["access_token"];
145125
}
146126
catch (Exception e)
147127
{
@@ -154,7 +134,7 @@ namespace Driver
154134
//
155135
string connString =
156136
String.Format(
157-
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer",
137+
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4}; SSLMode=Prefer",
158138
Host,
159139
User,
160140
Database,
@@ -184,12 +164,12 @@ namespace Driver
184164
When run, this command will give an output like this:
185165

186166
```
187-
Getting access token from Azure Instance Metadata service...
167+
Getting access token from Azure AD...
188168
Opening connection using access token...
189169
190170
Connected!
191171
192-
Postgres version: PostgreSQL 11.6, compiled by Visual C++ build 1800, 64-bit
172+
Postgres version: PostgreSQL 11.11, compiled by Visual C++ build 1800, 64-bit
193173
```
194174

195175
## Next steps

0 commit comments

Comments
 (0)