簡體   English   中英

如何使用PowerShell向Azure App注冊添加Api權限

[英]How to Add Api Permissions to an Azure App Registration using PowerShell

我弄清楚了 Azure PowerShell 中的命令,以將User.Read Ape 權限添加到我在 Azure 中的應用程序注冊中。

一個現有的應用程序

我可以找到一些使用*Azure的示例,但更喜歡使用*Az命令的示例,例如https://learn.microsoft.com/en-us/powershell/azure/?view=azps-2.8.0

想知道是否有人知道如何做到這一點? 謝謝!

目前只能使用Azure AD PowerShell來實現。 請注意Azure AD PowerShellAzure Z3D265B4E1EEEF0DDF178818CCZ之間存在差異 Azure AD PowerShell不僅僅是舊的 Azure Z3D265B4E1EEEF0DDF17881FA003模塊。 Azure AD PowerShell 是一個單獨的模塊。 Azure AD 還沒有“AZ*”。 只有幾個最常用的命令,它們具有 Azure 資源提供程序實現。 Azure PowerShell 具有與 Azure AD 一起使用的有限功能集。 如果您需要更多功能,例如您提到的功能,則必須使用 Azure AD PowerShell。 Azure AD PowerShell貶值,是官方支持的 PowerShell 模塊,用於與 Z3A580F1432203676F5F0ZBC 一起使用。

您可以通過Set-AzureAdApplication cmdlet 管理這些必需的權限並傳遞正確的-RequiredResourceAccess object。

為了構造這個 object,您必須首先獲得對“公開”權限的引用。 因為權限是由其他服務主體公開的。

因為我無法上傳整個文件,所以這里是一個 PowerShell 腳本,它創建了一個示例應用程序,該應用程序具有某些 MS Graph 所需的權限和一些 Power BI 權限。

Function GetToken
{
    param(
        [String] $authority = "https://login.microsoftonline.com/dayzure.com/oauth2/token",
        [String] $clientId,
        [String] $clientSecret,
        [String] $resourceId = "https://graph.windows.net"
    )
    $scope = [System.Web.HttpUtility]::UrlEncode($resourceId) 
    $encSecret = [System.Web.HttpUtility]::UrlEncode($clientSecret) 
    $body = "grant_type=client_credentials&resource=$($scope)&client_id=$($clientId)&client_secret=$($encSecret)"
    $res = Invoke-WebRequest -Uri $authority -Body $body -Method Post
    $authResult = $res.Content | ConvertFrom-Json
    return $authResult.access_token
}

#`
#            -RequiredResourceAccess @($requiredResourceAccess)
#

Function CreateChildApp
{
    param (
        [string] $displayName,
        [string] $tenantName
        )
    # create your new application
    Write-Output -InputObject ('Creating App Registration {0}' -f $displayName)
    if (!(Get-AzureADApplication -SearchString $displayName)) {
        $app = New-AzureADApplication -DisplayName $displayName `
            -Homepage "https://localhost" `
            -ReplyUrls "https://localhost" `
            -IdentifierUris ('https://{0}/{1}' -f $tenantName, $displayName) 

        # create SPN for App Registration
        Write-Output -InputObject ('Creating SPN for App Registration {0}' -f $displayName)

        # create a password (spn key)
        $appPwd = New-AzureADApplicationPasswordCredential -ObjectId $app.ObjectId
        $appPwd

        # create a service principal for your application
        # you need this to be able to grant your application the required permission
        $spForApp = New-AzureADServicePrincipal -AppId $app.AppId -PasswordCredentials @($appPwd)
    }
    else {
        Write-Output -InputObject ('App Registration {0} already exists' -f $displayName)
        $app = Get-AzureADApplication -SearchString $displayName
    }
    #endregion

    return $app
}

Function GrantAllThePermissionsWeWant
{
    param
    (
        [string] $targetServicePrincipalName,
        $appPermissionsRequired,
        $childApp,
        $spForApp
    )

    $targetSp = Get-AzureADServicePrincipal -Filter "DisplayName eq '$($targetServicePrincipalName)'"

    # Iterate Permissions array
    Write-Output -InputObject ('Retrieve Role Assignments objects')
    $RoleAssignments = @()
    Foreach ($AppPermission in $appPermissionsRequired) {
        $RoleAssignment = $targetSp.AppRoles | Where-Object { $_.Value -eq $AppPermission}
        $RoleAssignments += $RoleAssignment
    }

    $ResourceAccessObjects = New-Object 'System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess]'
    foreach ($RoleAssignment in $RoleAssignments) {
        $resourceAccess = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess"
        $resourceAccess.Id = $RoleAssignment.Id
        $resourceAccess.Type = 'Role'
        $ResourceAccessObjects.Add($resourceAccess)
    }
    $requiredResourceAccess = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
    $requiredResourceAccess.ResourceAppId = $targetSp.AppId
    $requiredResourceAccess.ResourceAccess = $ResourceAccessObjects

    # set the required resource access
    Set-AzureADApplication -ObjectId $childApp.ObjectId -RequiredResourceAccess $requiredResourceAccess
    Start-Sleep -s 1

    # grant the required resource access
    foreach ($RoleAssignment in $RoleAssignments) {
        Write-Output -InputObject ('Granting admin consent for App Role: {0}' -f $($RoleAssignment.Value))
        New-AzureADServiceAppRoleAssignment -ObjectId $spForApp.ObjectId -Id $RoleAssignment.Id -PrincipalId $spForApp.ObjectId -ResourceId $targetSp.ObjectId
        Start-Sleep -s 1
    }
}

cls

#globaladminapp
$clientID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
$key = "****"


$tenantId = "aaaaaaaa-bbbb-xxxx-yyyy-aaaaaaaaaaaa";
$TenantName = "customdomain.com";
$AppRegName = "globaladminChild-0003";

$token = GetToken -clientId $clientID -clientSecret $key

Disconnect-AzureAD
Connect-AzureAD -AadAccessToken $token -AccountId $clientID -TenantId $tenantId

$appPermissionsRequired = @('Application.ReadWrite.OwnedBy', 'Device.ReadWrite.All', 'Domain.ReadWrite.All')
$targetServicePrincipalName = 'Windows Azure Active Directory'

#$appPermissionsRequired = @('Files.ReadWrite.All','Sites.FullControl.All','Notes.ReadWrite.All')
#$targetServicePrincipalName = 'Microsoft Graph'

$app = CreateChildApp -displayName $AppRegName -tenantName $TenantName
$spForApp = Get-AzureADServicePrincipal -Filter "DisplayName eq '$($AppRegName)'"


$appPermissionsRequired = @('Tenant.ReadWrite.All')
$targetServicePrincipalName = 'Power BI Service'
GrantAllThePermissionsWeWant -targetServicePrincipalName $targetServicePrincipalName -appPermissionsRequired $appPermissionsRequired -childApp $app -spForApp $spForApp

$appPermissionsRequired = @('Files.ReadWrite.All','Sites.FullControl.All','Notes.ReadWrite.All')
$targetServicePrincipalName = 'Microsoft Graph'
GrantAllThePermissionsWeWant -targetServicePrincipalName $targetServicePrincipalName -appPermissionsRequired $appPermissionsRequired -childApp $app -spForApp $spForApp

有趣的部分是圍繞“apppermissionrequired”和“targetserviceprincipalname”變量。

我無法直接回復 Rolfo 的評論,因為我還沒有足夠的影響力。 確實,這並不簡單,但截至 2021 年 7 月,可以在同一個 session 中使用兩者。不確定情況是否總是如此,或者已更新某些內容以允許這樣做。

#Import modules if needed
$mList = @("AzureAD","Az.Resources","Az.Accounts")
foreach($m in $mList){if ((gmo -l $m).Count -eq 0){Install-Module -Name $m -AllowClobber -Scope CurrentUser -Force}}

#Authentication Popup
Connect-AzAccount

#Use authentication context cached from above to authenticate to AAD graph
$IDObject = Get-AzAccessToken -Resource "https://graph.windows.net"
Connect-AzureAD -AadAccessToken $IDObject.token -AccountId $IDObject.UserId

更新

使用新的圖形 API,我們可以使用以下命令將 API 權限添加到使用 PowerShell 的應用程序注冊/服務主體。它比舊過程簡單得多。

Add-AzADAppPermission -ApplicationId "$spId" -ApiId "00000009-0000-0000-c000-000000000000" -PermissionId "7504609f-c495-4c64-8542-686125a5a36f"

(PowerBI API就是這種情況)

如果通過 Azure Devops 管道進行部署,我通常建議使用以下腳本對 AAD 進行身份驗證:

  echo "Install Azure AD module..."
  Install-Module -Name "AzureAD" -Force
  Import-Module AzureAD -Force

  echo "Connect Azure AD..."
  $context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
  echo $context
  $graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
  echo $graphToken
  $aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
  Write-Output "Hi I'm $($context.Account.Id)"
  Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken
  echo "Connection ends"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM