src/Administration/Connect-XrmAdmin.ps1
|
. ([System.IO.Path]::Combine($PSScriptRoot, "..", "_Internals", "CryptoManager.ps1")) <# .SYNOPSIS Use Add-PowerAppsAccount cmdlet signs in the user or application account and saves the sign in information to cache. .DESCRIPTION Use this command to embed Power Apps Admin cmdlets The module Microsoft.PowerApps.Administration.PowerShell is loaded here, on first use, not when PowerDataOps is imported. It is not installed automatically: install it with Install-Module -Name Microsoft.PowerApps.Administration.PowerShell -Scope CurrentUser. Without parameter, the credentials of the current connection are used (user name and password, client secret or certificate); a connection without credentials (interactive, access token) gives an interactive sign-in, refused with an error when the session cannot show one. .PARAMETER UserName User login .PARAMETER Password User password .PARAMETER TenantId AAD tenant ID (use with ApplicationId / ClientSecret or CertificateThumbprint) .PARAMETER ApplicationId AAD Application ID .PARAMETER ClientSecret AAD Application secret .PARAMETER CertificateThumbprint AAD Application Certificate Thumbprint .PARAMETER IsEncrypted Specify if password or secret are encrypted. .OUTPUTS System.Void. The connection state is kept in $Global:XrmContext (IsAdminConnected), which the admin commands check. .EXAMPLE Connect-XrmAdmin -TenantId $tenantId -ApplicationId $applicationId -ClientSecret $clientSecret; $instances = Get-XrmInstances; .EXAMPLE $xrmClient = New-XrmClient -ConnectionString $connectionString; Connect-XrmAdmin; .LINK https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Connect-XrmAdmin.md #> function Connect-XrmAdmin { [CmdletBinding()] [OutputType([System.Void])] param ( [Parameter(Mandatory = $false)] [String] $UserName, [Parameter(Mandatory = $false)] [String] $Password, [Parameter(Mandatory = $false)] [String] $TenantId, [Parameter(Mandatory = $false)] [String] $ApplicationId, [Parameter(Mandatory = $false)] [String] $ClientSecret, [Parameter(Mandatory = $false)] [String] $CertificateThumbprint, [Parameter(Mandatory = $false)] [bool] $IsEncrypted = $false ) begin { $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); } process { Import-XrmPowerAppsAdminModuleInternal; $xrmConnection = $null; if($Global:XrmContext -and $Global:XrmContext.CurrentConnection){ $xrmConnection = $Global:XrmContext.CurrentConnection; } $hasCredentialParameters = ($PSBoundParameters.ContainsKey('UserName') -or $PSBoundParameters.ContainsKey('ClientSecret') -or $PSBoundParameters.ContainsKey('CertificateThumbprint')); if ($PSBoundParameters.ContainsKey('UserName')) { $xrmConnection = New-XrmConnection; $xrmConnection.AuthType = "Office365"; $xrmConnection.UserName = $UserName; if($IsEncrypted){ $xrmConnection.Password = Unprotect-XrmToolBoxPassword -EncryptedPassword $Password; } else{ $xrmConnection.Password = $Password; } } elseif ($PSBoundParameters.ContainsKey('ClientSecret')) { $xrmConnection = New-XrmConnection; $xrmConnection.AuthType = "ClientSecret"; $xrmConnection.TenantId = $TenantId; $xrmConnection.ApplicationId = $ApplicationId; if($IsEncrypted){ $xrmConnection.ClientSecret = Unprotect-XrmToolBoxPassword -EncryptedPassword $ClientSecret; } else{ $xrmConnection.ClientSecret = $ClientSecret; } } elseif ($PSBoundParameters.ContainsKey('CertificateThumbprint')) { $xrmConnection = New-XrmConnection; $xrmConnection.AuthType = "Certificate"; $xrmConnection.TenantId = $TenantId; $xrmConnection.ApplicationId = $ApplicationId; $xrmConnection.CertificateThumbprint = $CertificateThumbprint; } if (-not $Global:XrmContext) { $Global:XrmContext = New-XrmContext; } if ($xrmConnection) { $Global:XrmContext.CurrentConnection = $xrmConnection; } # Connect-XrmAdminInternal raises an error instead of returning $false (H23) $Global:XrmContext.IsAdminConnected = $false; $Global:XrmContext.IsAdminConnected = Connect-XrmAdminInternal -XrmConnection $xrmConnection; # IsEncrypted describes the secrets given here: a call without them keeps the value of the current connection if ($hasCredentialParameters) { $Global:XrmContext.IsEncrypted = $IsEncrypted; } } end { $StopWatch.Stop(); Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch; } } function Connect-XrmAdminInternal { [CmdletBinding()] param ( [Parameter(Mandatory = $false)] $XrmConnection, # For the tests: reason why the session cannot show an interactive sign-in (Get-XrmNonInteractiveReasonInternal by default) [Parameter(Mandatory = $false)] [string] $NonInteractiveReason = (Get-XrmNonInteractiveReasonInternal) ) begin { $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); } process { # This is just a wrapper for Power Apps admin connection # It could be done differently # I don't know if endpoint or audience are usefull here # https://docs.microsoft.com/en-us/powershell/module/microsoft.powerapps.administration.powershell/add-powerappsaccount?view=pa-ps-latest $xrmConnection = $XrmConnection; $authType = ([string]$xrmConnection.AuthType).ToLowerInvariant(); if ($authType -in @("oauth", "office365")) { if ($xrmConnection.Password) { $authType = "office365"; } elseif ($xrmConnection.ClientSecret) { $authType = "clientsecret"; } else { $authType = ""; } } # No credentials (interactive connection, access token, no connection): interactive sign-in. Before 2.0.0.77 it only # happened without any Dataverse connection; otherwise the function returned $false without error (H23) if ($authType -notin @("office365", "clientsecret", "certificate") -and $NonInteractiveReason) { throw "Connect-XrmAdmin needs credentials (-UserName and -Password, -TenantId -ApplicationId with -ClientSecret or -CertificateThumbprint) or an interactive sign-in, which this session cannot show: $NonInteractiveReason."; } # Force disconnect to refresh token $Global:currentSession = $null; Remove-PowerAppsAccount; # Force TLS 1.2 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; if ($authType -eq "office365") { $securePassword = ConvertTo-SecureString -String $xrmConnection.Password -AsPlainText -Force; Add-PowerAppsAccount -Username $xrmConnection.UserName -Password $securePassword -Endpoint prod; return $true; } elseif ($authType -eq "clientsecret") { Add-PowerAppsAccount -TenantID $xrmConnection.TenantId -ApplicationId $xrmConnection.ApplicationId -ClientSecret $xrmConnection.ClientSecret -Endpoint prod; return $true; } elseif ($authType -eq "certificate") { Add-PowerAppsAccount -TenantID $xrmConnection.TenantId -ApplicationId $xrmConnection.ApplicationId -CertificateThumbprint $xrmConnection.CertificateThumbprint -Endpoint prod; return $true; } Add-PowerAppsAccount -Endpoint prod; return $true; } end { $StopWatch.Stop(); Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch; } } Export-ModuleMember -Function Connect-XrmAdmin -Alias *; |