Создание скрипта автоматической установки для соединителя частной сети Microsoft Entra
В этой статье показано, как создать скрипт Windows PowerShell, который позволяет автоматически устанавливать и зарегистрировать соединитель частной сети Microsoft Entra.
Автоматическая установка полезна при желании:
- установить соединитель на серверах Windows, на которых отключен пользовательский интерфейс или к которым не удается получить доступ через удаленный рабочий стол;
- установить и зарегистрировать много соединителей одновременно;
- интегрировать установку и регистрацию соединителя в другую процедуру;
- Создайте стандартный образ сервера, содержащий биты соединителя, но не зарегистрирован.
Для работы соединителя частной сети необходимо зарегистрировать его с помощью идентификатора Microsoft Entra. Регистрация выполняется в пользовательском интерфейсе при установке соединителя, но для автоматизации процесса можно использовать PowerShell.
Этот процесс состоит из двух этапов. Сначала выполняется установка соединителя, Во-вторых, зарегистрируйте соединитель с помощью идентификатора Microsoft Entra.
Внимание
Если вы устанавливаете соединитель для облака Microsoft Azure для государственных организаций, ознакомьтесь с предварительными условиями и инструкциями по установке. В облаке Майкрософт Azure для государственных организаций требуется возможность доступа к другому набору URL-адресов и дополнительному параметру для запуска установки.
Установка соединителя
Чтобы установить соединитель без регистрации, сделайте следующее:
Откройте командную строку.
Выполните следующую команду,
/q
флаг означает тихую установку. и вам не нужно принимать лицензионное соглашение.MicrosoftEntraPrivateNetworkConnectorInstaller.exe REGISTERCONNECTOR="false" /q
Регистрация соединителя с помощью идентификатора Microsoft Entra
Зарегистрируйте соединитель с помощью маркера, созданного в автономном режиме.
Регистрация соединителя с помощью маркера, созданного в автономном режиме
Создайте автономный маркер с помощью класса с
AuthenticationContext
помощью значений в этом фрагменте кода или командлетах PowerShell:Для C#:
using System; using System.Linq; using System.Collections.Generic; using Microsoft.Identity.Client; class Program { #region constants /// <summary> /// The AAD authentication endpoint uri /// </summary> static readonly string AadAuthenticationEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"; /// <summary> /// The application ID of the connector in AAD /// </summary> static readonly string ConnectorAppId = "55747057-9b5d-4bd4-b387-abf52a8bd489"; /// <summary> /// The AppIdUri of the registration service in AAD /// </summary> static readonly string RegistrationServiceAppIdUri = "https://proxy.cloudwebappproxy.net/registerapp/user_impersonation"; #endregion #region private members private string token; private string tenantID; #endregion public void GetAuthenticationToken() { IPublicClientApplication clientApp = PublicClientApplicationBuilder .Create(ConnectorAppId) .WithDefaultRedirectUri() // will automatically use the default Uri for native app .WithAuthority(AadAuthenticationEndpoint) .Build(); AuthenticationResult authResult = null; IAccount account = null; IEnumerable<string> scopes = new string[] { RegistrationServiceAppIdUri }; try { authResult = await clientApp.AcquireTokenSilent(scopes, account).ExecuteAsync(); } catch (MsalUiRequiredException ex) { authResult = await clientApp.AcquireTokenInteractive(scopes).ExecuteAsync(); } if (authResult == null || string.IsNullOrEmpty(authResult.AccessToken) || string.IsNullOrEmpty(authResult.TenantId)) { Trace.TraceError("Authentication result, token or tenant id returned are null"); throw new InvalidOperationException("Authentication result, token or tenant id returned are null"); } token = authResult.AccessToken; tenantID = authResult.TenantId; } }
Использование PowerShell.
# Loading DLLs Find-PackageProvider -Name NuGet| Install-PackageProvider -Force Register-PackageSource -Name nuget.org -Location https://www.nuget.org/api/v2 -ProviderName NuGet Install-Package Microsoft.IdentityModel.Abstractions -ProviderName Nuget -RequiredVersion 6.22.0.0 Install-Module Microsoft.Identity.Client add-type -path "C:\Program Files\PackageManagement\NuGet\Packages\Microsoft.IdentityModel.Abstractions.6.22.0\lib\net461\Microsoft.IdentityModel.Abstractions.dll" add-type -path "C:\Program Files\WindowsPowerShell\Modules\Microsoft.Identity.Client\4.53.0\Microsoft.Identity.Client.dll" # The AAD authentication endpoint uri $authority = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" #The application ID of the connector in AAD $connectorAppId = "55747057-9b5d-4bd4-b387-abf52a8bd489"; #The AppIdUri of the registration service in AAD $registrationServiceAppIdUri = "https://proxy.cloudwebappproxy.net/registerapp/user_impersonation" # Define the resources and scopes you want to call $scopes = New-Object System.Collections.ObjectModel.Collection["string"] $scopes.Add($registrationServiceAppIdUri) $app = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($connectorAppId).WithAuthority($authority).WithDefaultRedirectUri().Build() [Microsoft.Identity.Client.IAccount] $account = $null # Acquiring the token $authResult = $null $authResult = $app.AcquireTokenInteractive($scopes).WithAccount($account).ExecuteAsync().ConfigureAwait($false).GetAwaiter().GetResult() # Check AuthN result If (($authResult) -and ($authResult.AccessToken) -and ($authResult.TenantId)) { $token = $authResult.AccessToken $tenantId = $authResult.TenantId Write-Output "Success: Authentication result returned." } Else { Write-Output "Error: Authentication result, token or tenant id returned with null." }
Создайте
SecureString
маркер с помощью маркера:$SecureToken = $Token | ConvertTo-SecureString -AsPlainText -Force
Выполните следующую команду Windows PowerShell, заменив
<tenant GUID>
идентификатором каталога..\RegisterConnector.ps1 -modulePath "C:\Program Files\Microsoft Entra private network connector\Modules\" -moduleName "MicrosoftEntraPrivateNetworkConnectorPSModule" -Authenticationmode Token -Token $SecureToken -TenantId <tenant GUID> -Feature ApplicationProxy
Сохраните скрипт или код в безопасном расположении, так как оно содержит конфиденциальные учетные данные.