Можно ли использовать токен AccessToken или Identity в качестве учетных данных для Connect-AzureAD / MSGraph?

У меня есть мультитенантное приложение AzureAD, которое вызывает ряд сценариев PowerShell в контексте вошедшего в систему пользователя моего веб-приложения.

Можно ли передать AccessToken или IDToken в сценарий PowerShell и создать сеанс с помощью командлета Connect-AzureAD?

Я вижу перегрузку учетных данных, и, возможно, есть способ использовать (или преобразовать) токен во что-то, что можно использовать с этим параметром?

PS C:\Users> get-help connect-azuread -examples

NAME
Connect-AzureAD

SYNOPSIS
Connects with an authenticated account to use Active Directory cmdlet requests.


Example 1: Connect a PowerShell session to a tenant

PS C:\> Connect-AzureAD -Confirm

This command connects the current PowerShell session to an Azure Active Directory tenant. The command prompts you
for a username and password for the tenant you want to connect to. The Confirm parameter prompts you for
confirmation.

If multi-factor authentication is enabled for your credentials, you must log in using the interactive option or
use service principal authentication.
Example 2: Connect a session using a variable

PS C:\> $Credential = Get-Credential
PS C:\> Connect-AzureAD -Credential $Credential

The first command gets the user credentials, and then stores them in the $Credential variable.

The second command connects the current PowerShell session using the credentials in $Credential.

This account authenticates with Azure Active Directory using organizational ID credentials. You cannot use
multi-factor authentication or Microsoft account credentials to run Azure Active Directory cmdlets with this
account.
Example 3: Connect a session as a service principal

# Login to Azure AD PowerShell With Admin Account
Connect-AzureAD

# Create the self signed cert
$currentDate = Get-Date
$endDate = $currentDate.AddYears(1)
$notAfter = $endDate.AddYears(1)
$pwd = "<password>"
$thumb = (New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my -DnsName com.foo.bar -KeyExportPolicy
Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
$pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
Export-PfxCertificate -cert "cert:\localmachine\my\$thumb" -FilePath c:\temp\examplecert.pfx -Password $pwd

# Load the certificate
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("C:\temp\examplecert.pfx", $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())


# Create the Azure Active Directory Application
$application = New-AzureADApplication -DisplayName "test123" -IdentifierUris "https://test123"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "Test123" -StartDate
$currentDate -EndDate $endDate -Type AsymmetricX509Cert -Usage Verify -Value $keyValue

# Create the Service Principal and connect it to the Application
$sp=New-AzureADServicePrincipal -AppId $application.AppId

# Give the Service Principal Reader access to the current tenant (Get-AzureADDirectoryRole)
Add-AzureADDirectoryRoleMember -ObjectId 5997d714-c3b5-4d5b-9973-ec2f38fd49d5 -RefObjectId $sp.ObjectId

# Get Tenant Detail
$tenant=Get-AzureADTenantDetail
# Now you can login to Azure PowerShell with your Service Principal and Certificate
Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId  $sp.AppId -CertificateThumbprint $thumb

This command authenticates the user to Azure Active Directory as a service principal.

comment
Если вы проверите параметры, вы можете сделать, например, Connect-AzureAD -MsAccessToken $token так что я полагаю, это сработает. Однако вы не можете использовать токен Id. Вам понадобится токен доступа либо для MS Graph API, либо для AAD Graph API, в зависимости от того, какой API использует конкретный командлет, который вы хотите использовать.   -  person juunas    schedule 13.05.2020
comment
@juunas Спасибо. Мой мозг искажается, когда я пытаюсь выяснить поток аутентификации из Blazor Webassembly (это как Xamarin или Javascript) ... тогда как мне использовать это для вызова AD API ... который вызывает серверную часть PowerShell ... который вызывает GraphAPI   -  person CMEdge    schedule 13.05.2020


Ответы (2)


Вот простой пример :

Connect-AzureAD
       -TenantId {Tenant ID}
       -AadAccessToken {AAD Graph Access Token}
       -MsAccessToken {Microsoft Graph Access Token}
       -AccountId {Your UPN}

Обратите внимание: если вы должны предоставить AadAccessToke, потому что вы подключаетесь к модулю AAD.

MsAccessToken не является обязательным. Но если вам нужно использовать некоторые cmds, для которых требуется разрешение Microsoft Graph, вы должны предоставить MsAccessToken. Пример - Get-AzureADPolicy.

Здесь можно использовать только токен доступа. Идентификационный токен не поддерживается.

person Allen Wu    schedule 14.05.2020

Последний параметр, установленный в docs описывает AADAccessToken параметр.

Connect-AzureAD
       [-AzureEnvironmentName <EnvironmentName>]
       [-TenantId <String>]
       -AadAccessToken <String>
       [-MsAccessToken <String>]
       -AccountId <String>
       [-LogLevel <LogLevel>]
       [-LogFilePath <String>]
       [-InformationAction <ActionPreference>]
       [-InformationVariable <String>]
       [-WhatIf]
       [-Confirm]
       [<CommonParameters>]

Вы можете использовать access token в командлете PowerShell Connect-AzureAD для подключения к Azure AD. Но это должен быть токен доступа, а не id. И его аудиторией должен быть Microsoft Graph.

person astaykov    schedule 14.05.2020