Skip to content

Commit a7edaee

Browse files
authored
Merge pull request #115206 from lfittl-msft/mysql-postgres-aad-managed-identity
Add Managed Identity how to articles for MySQL and PostgreSQL
2 parents 9dddcc7 + 58194b3 commit a7edaee

File tree

4 files changed

+400
-0
lines changed

4 files changed

+400
-0
lines changed

articles/mysql/TOC.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,8 @@
276276
items:
277277
- name: Configure Azure AD integration
278278
href: howto-configure-sign-in-azure-ad-authentication.md
279+
- name: Connect with Managed Identity
280+
href: howto-connect-with-managed-identity.md
279281
- name: Deny Public Network Access
280282
items:
281283
- name: Azure portal
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
---
2+
title: Connect with Managed Identity - Azure Database for MySQL
3+
description: Learn about how to connect and authenticate using Managed Identity for authentication with Azure Database for MySQL
4+
author: lfittl-msft
5+
ms.author: lufittl
6+
ms.service: mysql
7+
ms.topic: conceptual
8+
ms.date: 05/19/2020
9+
---
10+
11+
# Connect with Managed Identity to Azure Database for MySQL
12+
13+
This article shows you how to use a user-assigned identity for an Azure Virtual Machine (VM) to access an Azure Database for MySQL 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. You learn how to:
14+
15+
> [!div class="checklist"]
16+
> * Grant your VM access to an Azure Database for MySQL server
17+
> * Create a user in the database that represents the VM's user-assigned identity
18+
> * Get an access token using the VM identity and use it to query an Azure Database for MySQL server
19+
> * Implement the token retrieval in a C# example application
20+
21+
## Prerequisites
22+
23+
- 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.
24+
- To do the required resource creation and role management, your account needs "Owner" permissions at the appropriate scope (your subscription or resource group). If you need assistance with role assignment, see [Use Role-Based Access Control to manage access to your Azure subscription resources](../../articles/role-based-access-control/role-assignments-portal.md).
25+
- You need an Azure VM (for example running Ubuntu Linux) that you'd like to use for access your database using Managed Identity
26+
- You need an Azure Database for MySQL database server that has [Azure AD authentication](howto-configure-sign-in-azure-ad-authentication.md) configured
27+
- To follow the C# example, first complete the guide how to [Connect using C#](connect-csharp.md)
28+
29+
## Creating a user-assigned managed identity for your VM
30+
31+
Create an identity in your subscription using the [az identity create](/cli/azure/identity?view=azure-cli-latest#az-identity-create) command. You can use the same resource group that your virtual machine runs in, or a different one.
32+
33+
```azurecli-interactive
34+
az identity create --resource-group myResourceGroup --name myManagedIdentity
35+
```
36+
37+
To configure the identity in the following steps, use the [az identity show](/cli/azure/identity?view=azure-cli-latest#az-identity-show) command to store the identity's resource ID and client ID in variables.
38+
39+
```azurecli
40+
# Get resource ID of the user-assigned identity
41+
resourceID=$(az identity show --resource-group myResourceGroup --name myManagedIdentity --query id --output tsv)
42+
43+
# Get client ID of the user-assigned identity
44+
clientID=$(az identity show --resource-group myResourceGroup --name myManagedIdentity --query clientId --output tsv)
45+
```
46+
47+
We can now assign the user-assigned identity to the VM with the [az vm identity assign](/cli/azure/vm/identity?view=azure-cli-latest#az-vm-identity-assign) command:
48+
49+
```azurecli
50+
az vm identity assign --resource-group myResourceGroup --name myVM --identities $resourceID
51+
```
52+
53+
To finish setup, show the value of the Client ID, which you'll need in the next few steps:
54+
55+
```bash
56+
echo $clientID
57+
```
58+
59+
## Creating a MySQL user for your Managed Identity
60+
61+
Now, connect as the Azure AD administrator user to your MySQL database, and run the following SQL statements:
62+
63+
```sql
64+
SET aad_auth_validate_oids_in_tenant = OFF;
65+
CREATE AADUSER 'myuser' IDENTIFIED BY 'CLIENT_ID';
66+
```
67+
68+
The managed identity now has access when authenticating with the username `myuser` (replace with a name of your choice).
69+
70+
## Retrieving the access token from Azure Instance Metadata service
71+
72+
Your application can now retrieve an access token from the Azure Instance Metadata service and use it for authenticating with the database.
73+
74+
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:
75+
76+
* `api-version` = `2018-02-01`
77+
* `resource` = `https://ossrdbms-aad.database.windows.net`
78+
* `client_id` = `CLIENT_ID` (that you retrieved earlier)
79+
80+
You'll get back a JSON result that contains an `access_token` field - this long text value is the Managed Identity access token, that you should use as the password when connecting to the database.
81+
82+
For testing purposes, you can run the following commands in your shell. Note you need `curl`, `jq`, and the `mysql` client installed.
83+
84+
```bash
85+
# Retrieve the access token
86+
accessToken=$(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)
87+
88+
# Connect to the database
89+
mysql -h SERVER --user USER@SERVER --enable-cleartext-plugin --password=$accessToken
90+
```
91+
92+
You are now connected to the database you've configured earlier.
93+
94+
## Connecting using Managed Identity in C#
95+
96+
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 MySQL. Azure Database for MySQL natively supports Azure AD authentication, so it can directly accept access tokens obtained using managed identities for Azure resources. When creating a connection to MySQL, you pass the access token in the password field.
97+
98+
Here's a .NET code example of opening a connection to MySQL 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.
99+
100+
```csharp
101+
using System;
102+
using System.Net;
103+
using System.IO;
104+
using System.Collections;
105+
using System.Collections.Generic;
106+
using System.Text.Json;
107+
using System.Text.Json.Serialization;
108+
using System.Threading.Tasks;
109+
using MySql.Data.MySqlClient;
110+
111+
namespace Driver
112+
{
113+
class Script
114+
{
115+
// Obtain connection string information from the portal
116+
//
117+
private static string Host = "HOST";
118+
private static string User = "USER";
119+
private static string Database = "DATABASE";
120+
private static string ClientId = "CLIENT_ID";
121+
122+
static async Task Main(string[] args)
123+
{
124+
//
125+
// Get an access token for MySQL.
126+
//
127+
Console.Out.WriteLine("Getting access token from Azure Instance Metadata service...");
128+
129+
// Azure AD resource ID for Azure Database for MySQL 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";
133+
string accessToken = null;
134+
135+
try
136+
{
137+
// Call managed identities for Azure resources endpoint.
138+
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
139+
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"];
145+
}
146+
catch (Exception e)
147+
{
148+
Console.Out.WriteLine("{0} \n\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : "Acquire token failed");
149+
System.Environment.Exit(1);
150+
}
151+
152+
//
153+
// Open a connection to the MySQL server using the access token.
154+
//
155+
var builder = new MySqlConnectionStringBuilder
156+
{
157+
Server = Host,
158+
Database = Database,
159+
UserID = User,
160+
Password = accessToken,
161+
SslMode = MySqlSslMode.Required,
162+
};
163+
164+
using (var conn = new MySqlConnection(builder.ConnectionString))
165+
{
166+
Console.Out.WriteLine("Opening connection using access token...");
167+
await conn.OpenAsync();
168+
169+
using (var command = conn.CreateCommand())
170+
{
171+
command.CommandText = "SELECT VERSION()";
172+
173+
using (var reader = await command.ExecuteReaderAsync())
174+
{
175+
while (await reader.ReadAsync())
176+
{
177+
Console.WriteLine("\nConnected!\n\nMySQL version: {0}", reader.GetString(0));
178+
}
179+
}
180+
}
181+
}
182+
}
183+
}
184+
}
185+
```
186+
187+
When run, this command will give an output like this:
188+
189+
```
190+
Getting access token from Azure Instance Metadata service...
191+
Opening connection using access token...
192+
193+
Connected!
194+
195+
MySQL version: 5.7.27
196+
```
197+
198+
## Next steps
199+
200+
* Review the overall concepts for [Azure Active Directory authentication with Azure Database for MySQL](concepts-azure-ad-authentication.md)

articles/postgresql/TOC.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,8 @@
200200
href: howto-create-users.md
201201
- name: Configure Azure AD integration
202202
href: howto-configure-sign-in-aad-authentication.md
203+
- name: Connect with Managed Identity
204+
href: howto-connect-with-managed-identity.md
203205
- name: Optimize
204206
items:
205207
- name: Bulk inserts

0 commit comments

Comments
 (0)