Access database windows azure

Tutorial: Use a Windows VM system-assigned managed identity to access Azure SQL

Managed identities for Azure resources is a feature of Azure Active Directory. Each of the Azure services that support managed identities for Azure resources are subject to their own timeline. Make sure you review the availability status of managed identities for your resource and known issues before you begin.

This tutorial shows you how to use a system-assigned identity for a Windows virtual machine (VM) to access Azure SQL Database. 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:

  • Grant your VM access to Azure SQL Database
  • Enable Azure AD authentication
  • Create a contained user in the database that represents the VM’s system assigned identity
  • Get an access token using the VM identity and use it to query Azure SQL Database

Prerequisites

  • If you’re not familiar with the managed identities for Azure resources feature, see this overview.
  • If you don’t have an Azure account, sign up for a free account before you continue.
  • To perform 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 Assign Azure roles to manage access to your Azure subscription resources.

Enable

Enabling a system-assigned managed identity is a one-click experience. You can either enable it during the creation of a VM or in the properties of an existing VM.

To enable a system-assigned managed identity on a new VM:

Grant access

To grant your VM access to a database in Azure SQL Database, you can use an existing logical SQL server or create a new one. To create a new server and database using the Azure portal, follow this Azure SQL quickstart. There are also quickstarts that use the Azure CLI and Azure PowerShell in the Azure SQL documentation.

There are two steps to granting your VM access to a database:

  1. Enable Azure AD authentication for the server.
  2. Create a contained user in the database that represents the VM’s system-assigned identity.

Enable Azure AD authentication

  1. In the Azure portal, select SQL servers from the left-hand navigation.
  2. Click the SQL server to be enabled for Azure AD authentication.
  3. In the Settings section of the blade, click Active Directory admin.
  4. In the command bar, click Set admin.
  5. Select an Azure AD user account to be made an administrator of the server, and click Select.
  6. In the command bar, click Save.

Create contained user

This section shows how to create a contained user in the database that represents the VM’s system assigned identity. For this step, you need Microsoft SQL Server Management Studio (SSMS). Before beginning, it may also be helpful to review the following articles for background on Azure AD integration:

SQL DB requires unique AAD display names. With this, the AAD accounts such as users, groups and Service Principals (applications), and VM names enabled for managed identity must be uniquely defined in AAD regarding their display names. SQL DB checks the AAD display name during T-SQL creation of such users and if it is not unique, the command fails requesting to provide a unique AAD display name for a given account.

To create a contained user:

Start SQL Server Management Studio.

In the Connect to Server dialog, Enter your server name in the Server name field.

In the Authentication field, select Active Directory — Universal with MFA support.

In the User name field, enter the name of the Azure AD account that you set as the server administrator, for example, helen@woodgroveonline.com

Click Options.

In the Connect to database field, enter the name of the non-system database you want to configure.

Click Connect. Complete the sign-in process.

In the Object Explorer, expand the Databases folder.

Right-click on a user database and click New query.

In the query window, enter the following line, and click Execute in the toolbar:

VMName in the following command is the name of the VM that you enabled system assigned identity on in the prerequsites section.

The command should complete successfully, creating the contained user for the VM’s system-assigned identity.

Clear the query window, enter the following line, and click Execute in the toolbar:

VMName in the following command is the name of the VM that you enabled system assigned identity on in the prerequsites section.

The command should complete successfully, granting the contained user the ability to read the entire database.

Code running in the VM can now get a token using its system-assigned managed identity and use the token to authenticate to the server.

Читайте также:  To system windows dependencyproperty

Access data

This section shows how to get an access token using the VM’s system-assigned managed identity and use it to call Azure SQL. Azure SQL natively supports Azure AD authentication, so it can directly accept access tokens obtained using managed identities for Azure resources. You use the access token method of creating a connection to SQL. This is part of Azure SQL’s integration with Azure AD, and is different from supplying credentials on the connection string.

Here’s a .NET code example of opening a connection to SQL using an access token. The code must run on the VM to be able to access the VM’s system-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 AZURE-SQL-SERVERNAME and DATABASE accordingly. Note the resource ID for Azure SQL is https://database.windows.net/ .

Alternatively, a quick way to test the end to end setup without having to write and deploy an app on the VM is using PowerShell.

In the portal, navigate to Virtual Machines and go to your Windows virtual machine and in the Overview, click Connect.

Enter in your Username and Password for which you added when you created the Windows VM.

Now that you have created a Remote Desktop Connection with the virtual machine, open PowerShell in the remote session.

Using PowerShell’s Invoke-WebRequest , make a request to the local managed identity’s endpoint to get an access token for Azure SQL.

Convert the response from a JSON object to a PowerShell object.

Extract the access token from the response.

Open a connection to the server. Remember to replace the values for AZURE-SQL-SERVERNAME and DATABASE.

Next, create and send a query to the server. Remember to replace the value for TABLE.

Examine the value of $DataSet.Tables[0] to view the results of the query.

Disable

To disable the system-assigned identity on your VM, set the status of the system-assigned identity to Off.

Next steps

In this tutorial, you learned how to use a system-assigned managed identity to access Azure SQL Database. To learn more about Azure SQL Database see:

Руководство по Использование назначаемого системой управляемого удостоверения на виртуальной машине Windows для доступа к SQL Azure Tutorial: Use a Windows VM system-assigned managed identity to access Azure SQL

Управляемые удостоверения для ресурсов Azure — это функция Azure Active Directory. Managed identities for Azure resources is a feature of Azure Active Directory. Каждая служба Azure, которая поддерживает управляемые удостоверения для ресурсов Azure, используется в соответствии с собственной временной шкалой. Each of the Azure services that support managed identities for Azure resources are subject to their own timeline. Прежде чем начать работу, обязательно проверьте состояние доступности управляемых удостоверений для своего ресурса и ознакомьтесь с известными проблемами. Make sure you review the availability status of managed identities for your resource and known issues before you begin.

В этом руководстве описывается, как получить доступ к Базе данных SQL Azure с помощью назначаемого системой удостоверения виртуальной машины Windows. This tutorial shows you how to use a system-assigned identity for a Windows virtual machine (VM) to access Azure SQL Database. Управляемыми удостоверениями службы автоматически управляет Azure. Они позволяют проходить проверку подлинности в службах, поддерживающих аутентификацию Azure AD, без указания учетных данных в коде. 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:

  • Предоставление виртуальной машине доступа к Базе данных SQL Azure Grant your VM access to Azure SQL Database
  • Включение аутентификации Azure AD Enable Azure AD authentication
  • Создание в базе данных автономного пользователя, который представляет назначаемое системой удостоверение виртуальной машины Create a contained user in the database that represents the VM’s system assigned identity
  • Получение маркера доступа с использованием удостоверения виртуальной машины и отправка запроса в Базу данных SQL Azure с его помощью Get an access token using the VM identity and use it to query Azure SQL Database

Предварительные требования Prerequisites

  • См. дополнительные сведения об управляемых удостоверениях для ресурсов Azure. If you’re not familiar with the managed identities for Azure resources feature, see this overview.
  • Если у вас нет учетной записи Azure, зарегистрируйтесь для получения бесплатной учетной записи, прежде чем продолжить. If you don’t have an Azure account, sign up for a free account before you continue.
  • Для выполнения требуемых операций создания ресурсов и управления ролями учетной записи нужно предоставить разрешения роли «Владелец» в соответствующей области (подписка или группа ресурсов). To perform the required resource creation and role management, your account needs «Owner» permissions at the appropriate scope (your subscription or resource group). Если нуждаетесь в помощи с назначением ролей, прочитайте статью Назначение ролей Azure с помощью портала Azure. If you need assistance with role assignment, see Assign Azure roles to manage access to your Azure subscription resources.

Включить Enable

Включить управляемое удостоверение, назначаемое системой, можно одним щелчком мыши. Enabling a system-assigned managed identity is a one-click experience. Это можно сделать при создании виртуальной машины или в свойствах существующей виртуальной машины. You can either enable it during the creation of a VM or in the properties of an existing VM.

Читайте также:  Ошибка windows memory dmp код отчета

Чтобы включить управляемое удостоверение, назначаемое системой, для новой виртуальной машины, сделайте следующее: To enable a system-assigned managed identity on a new VM:

Предоставление доступа Grant access

Чтобы предоставить виртуальной машине доступ к Базе данных SQL Azure, можно использовать существующий логический сервер SQL Server или создать новый. To grant your VM access to a database in Azure SQL Database, you can use an existing logical SQL server or create a new one. Чтобы создать сервер и базу данных с помощью портала Azure, следуйте указаниям в статье Создание базы данных SQL Azure на портале Azure. To create a new server and database using the Azure portal, follow this Azure SQL quickstart. В документации по SQL Azure также есть краткие руководства, описывающие использование Azure CLI и Azure PowerShell. There are also quickstarts that use the Azure CLI and Azure PowerShell in the Azure SQL documentation.

Предоставление виртуальной машине доступа к базе данных выполняется в два этапа: There are two steps to granting your VM access to a database:

  1. Включение аутентификации Azure AD для сервера. Enable Azure AD authentication for the server.
  2. Создание в базе данных автономного пользователя, который представляет назначаемое системой удостоверение виртуальной машины. Create a contained user in the database that represents the VM’s system-assigned identity.

Включение аутентификации Azure AD Enable Azure AD authentication

Для настройки аутентификации Azure AD выполните указанные ниже действия. To configure Azure AD authentication:

  1. На портале Azure выберите SQL servers (Серверы SQL Server) на левой панели навигации. In the Azure portal, select SQL servers from the left-hand navigation.
  2. Щелкните сервер SQL, для которого нужно включить аутентификацию Azure AD. Click the SQL server to be enabled for Azure AD authentication.
  3. В разделе колонки Параметры щелкните Администратор Active Directory. In the Settings section of the blade, click Active Directory admin.
  4. В командной строке щелкните Задать администратора. In the command bar, click Set admin.
  5. Выберите учетную запись пользователя Azure AD, которую необходимо сделать администратором сервера, а затем нажмите кнопку Выбрать. Select an Azure AD user account to be made an administrator of the server, and click Select.
  6. На панели команд нажмите кнопку Сохранить. In the command bar, click Save.

Создание автономного пользователя Create contained user

В этом разделе показано, как в базе данных создать автономного пользователя, который представляет назначаемое системой удостоверение виртуальной машины. This section shows how to create a contained user in the database that represents the VM’s system assigned identity. На этом шаге вам потребуется Microsoft SQL Server Management Studio (SSMS). For this step, you need Microsoft SQL Server Management Studio (SSMS). Прежде чем начать, советуем ознакомиться со следующими статьями, содержащими общие сведения об интеграции Azure AD: Before beginning, it may also be helpful to review the following articles for background on Azure AD integration:

Для базы данных SQL в AAD требуются уникальные отображаемые имена. SQL DB requires unique AAD display names. Поэтому учетные записи AAD, например пользователей, групп и субъектов-служб (приложения), и имена виртуальных машин, которые включены для управляемого удостоверения, должны иметь уникальные отображаемые имена в AAD. With this, the AAD accounts such as users, groups and Service Principals (applications), and VM names enabled for managed identity must be uniquely defined in AAD regarding their display names. База данных SQL проверяет отображаемое имя AAD при создании таких пользователей на языке T-SQL. Если имя не является уникальным, команда завершается ошибкой и отображается запрос на ввод уникального отображаемого имени AAD для этой учетной записи. SQL DB checks the AAD display name during T-SQL creation of such users and if it is not unique, the command fails requesting to provide a unique AAD display name for a given account.

Чтобы создать автономного пользователя, сделайте следующее: To create a contained user:

Запустите среду SQL Server Management Studio. Start SQL Server Management Studio.

В диалоговом окне Подключение к серверу в поле Имя сервера введите имя сервера. In the Connect to Server dialog, Enter your server name in the Server name field.

В поле Authentication (Аутентификация) выберите Active Directory — универсальная с поддержкой MFA. In the Authentication field, select Active Directory — Universal with MFA support.

В поле Имя пользователя введите имя учетной записи Azure AD, установленной в качестве администратора сервера, например helen@woodgroveonline.com. In the User name field, enter the name of the Azure AD account that you set as the server administrator, for example, helen@woodgroveonline.com

Щелкните Параметры. Click Options.

В поле Подключение к базе данных введите имя несистемной базы данных, которую требуется настроить. In the Connect to database field, enter the name of the non-system database you want to configure.

Нажмите кнопку Соединить. Click Connect. Завершите процесс входа в систему. Complete the sign-in process.

В обозревателе объектов разверните папку Базы данных. In the Object Explorer, expand the Databases folder.

Щелкните правой кнопкой мыши пользовательскую базу данных и выберите Создать запрос. Right-click on a user database and click New query.

В окне запроса введите следующую строку и на панели инструментов нажмите кнопку Выполнить. In the query window, enter the following line, and click Execute in the toolbar:

В приведенной ниже команде VMName — это имя виртуальной машины, для которой вы ранее настроили назначаемое системой удостоверение. VMName in the following command is the name of the VM that you enabled system assigned identity on in the prerequsites section.

Читайте также:  Драйвер сканер для samsung scx 4220 для windows

В результате выполнения команды должен быть создан автономный пользователь для назначаемого системой удостоверения виртуальной машины. The command should complete successfully, creating the contained user for the VM’s system-assigned identity.

Очистите окно запроса, введите следующую строку и на панели инструментов нажмите кнопку Выполнить. Clear the query window, enter the following line, and click Execute in the toolbar:

В приведенной ниже команде VMName — это имя виртуальной машины, для которой вы ранее настроили назначаемое системой удостоверение. VMName in the following command is the name of the VM that you enabled system assigned identity on in the prerequsites section.

В результате выполнения команды автономному пользователю должна быть предоставлена возможность считывания всей базы данных. The command should complete successfully, granting the contained user the ability to read the entire database.

Теперь код, запущенный на виртуальной машине, может с помощью назначаемого системой управляемого удостоверения получить маркер и использовать его для аутентификации на сервере. Code running in the VM can now get a token using its system-assigned managed identity and use the token to authenticate to the server.

Доступ к данным Access data

В этом разделе показано, как получить маркер доступа с помощью назначаемого системой управляемого удостоверения виртуальной машины и использовать этот маркер для обращения к SQL Azure. This section shows how to get an access token using the VM’s system-assigned managed identity and use it to call Azure SQL. В SQL Azure реализована поддержка аутентификации Azure AD, поэтому поддерживается непосредственный прием маркеров доступа, полученных с использованием управляемого удостоверения. Azure SQL natively supports Azure AD authentication, so it can directly accept access tokens obtained using managed identities for Azure resources. Для создания подключения к SQL используется метод на основе маркера доступа. You use the access token method of creating a connection to SQL. Он реализуется как часть интеграции SQL Azure с Azure AD и отличается от указания учетных данных в строке подключения. This is part of Azure SQL’s integration with Azure AD, and is different from supplying credentials on the connection string.

Ниже приведен пример кода .NET для установки подключения к SQL с помощью маркера доступа. Here’s a .NET code example of opening a connection to SQL using an access token. Этот код должен выполняться на виртуальной машине, чтобы обеспечить возможность доступа к конечной точке назначаемого системой управляемого удостоверения виртуальной машины. The code must run on the VM to be able to access the VM’s system-assigned managed identity’s endpoint. Для использования метода с маркером доступа требуется .NET Framework 4.6 или более поздней версии либо .NET Core 2.2 или более поздней версии. .NET Framework 4.6 or higher or .NET Core 2.2 or higher is required to use the access token method. Замените значения AZURE-SQL-SERVERNAME и DATABASE соответствующим образом. Replace the values of AZURE-SQL-SERVERNAME and DATABASE accordingly. Обратите внимание на то, что идентификатор ресурса для SQL Azure — https://database.windows.net/ . Note the resource ID for Azure SQL is https://database.windows.net/ .

Кроме того, вы можете быстро протестировать сквозную настройку с помощью PowerShell без необходимости писать и развертывать приложение на виртуальной машине. Alternatively, a quick way to test the end to end setup without having to write and deploy an app on the VM is using PowerShell.

На портале перейдите к разделу Виртуальные машины, выберите свою виртуальную машину Windows и в разделе Обзор щелкните Подключить. In the portal, navigate to Virtual Machines and go to your Windows virtual machine and in the Overview, click Connect.

Введите имя пользователя и пароль, добавленные при создании виртуальной машины Windows. Enter in your Username and Password for which you added when you created the Windows VM.

Теперь, когда создано подключение к удаленному рабочему столу с виртуальной машиной, откройте PowerShell в удаленном сеансе. Now that you have created a Remote Desktop Connection with the virtual machine, open PowerShell in the remote session.

С помощью команды PowerShell Invoke-WebRequest выполните запрос к локальной конечной точке управляемого удостоверения, чтобы получить маркер доступа к SQL Azure. Using PowerShell’s Invoke-WebRequest , make a request to the local managed identity’s endpoint to get an access token for Azure SQL.

Преобразуйте ответ из объекта JSON в объект PowerShell. Convert the response from a JSON object to a PowerShell object.

Извлеките маркер доступа из ответа. Extract the access token from the response.

Установите подключение к серверу. Open a connection to the server. Не забудьте заменить значения AZURE-SQL-SERVERNAME и DATABASE. Remember to replace the values for AZURE-SQL-SERVERNAME and DATABASE.

Затем создайте и отправьте запрос на сервер. Next, create and send a query to the server. Не забудьте заменить значение для TABLE. Remember to replace the value for TABLE.

Проверьте значение $DataSet.Tables[0] , чтобы просмотреть результаты запроса. Examine the value of $DataSet.Tables[0] to view the results of the query.

Отключить Disable

Чтобы отключить назначенное системой удостоверение на виртуальной машине, задайте значение отключено для состояния назначенного системой удостоверения. To disable the system-assigned identity on your VM, set the status of the system-assigned identity to Off.

Дальнейшие действия Next steps

Из этого руководства вы узнали, как создать назначаемое системой управляемое удостоверение и получить доступ к Базе данных SQL Azure. In this tutorial, you learned how to use a system-assigned managed identity to access Azure SQL Database. См. дополнительные сведения о Базе данных SQL Azure: To learn more about Azure SQL Database see:

Оцените статью