[英]How to Add Api Permissions to an Azure App Registration using PowerShell
I am figure out the commands in Azure PowerShell to add an the User.Read
Ape Permission to my App Registration in Azure.我弄清楚了 Azure PowerShell 中的命令,以将
User.Read
Ape 权限添加到我在 Azure 中的应用程序注册中。
I can find some examples using *Azure
, but would prefer one that uses the *Az
commands, eg https://learn.microsoft.com/en-us/powershell/azure/?view=azps-2.8.0 .我可以找到一些使用
*Azure
的示例,但更喜欢使用*Az
命令的示例,例如https://learn.microsoft.com/en-us/powershell/azure/?view=azps-2.8.0 。
Wonder if anybody knows how to do this?想知道是否有人知道如何做到这一点? Thanks!
谢谢!
This can currently only be achieved using the Azure AD PowerShell .目前只能使用Azure AD PowerShell来实现。 Please note that there is a difference between Azure AD PowerShell and Azure PowerShell .
请注意Azure AD PowerShell和Azure Z3D265B4E1EEEF0DDF178818CCZ之间存在差异The Azure AD PowerShell is not simply the old Azure PowerShell module.
Azure AD PowerShell不仅仅是旧的 Azure Z3D265B4E1EEEF0DDF17881FA003模块。 Azure AD PowerShell is a separate module.
Azure AD PowerShell 是一个单独的模块。 There is no "AZ*" for Azure AD yet.
Azure AD 还没有“AZ*”。 Only couple of most commonly used commands , that have Azure Resource Provider implementation.
只有几个最常用的命令,它们具有 Azure 资源提供程序实现。 Azure PowerShell has a limited set of features for working with Azure AD.
Azure PowerShell 具有与 Azure AD 一起使用的有限功能集。 If you need more features, like the one you mention, you must use Azure AD PowerShell.
如果您需要更多功能,例如您提到的功能,则必须使用 Azure AD PowerShell。 Azure AD PowerShell is not depricated and is the officially supported PowerShell module for working with Azure AD.
Azure AD PowerShell未贬值,是官方支持的 PowerShell 模块,用于与 Z3A580F1432203676F5F0ZBC 一起使用。
You can manage these required permissions by the Set-AzureAdApplication cmdlet and passing proper -RequiredResourceAccess
object.您可以通过Set-AzureAdApplication cmdlet 管理这些必需的权限并传递正确的
-RequiredResourceAccess
object。
In order to construct this object, you must first get a reference to "exposed" permissions.为了构造这个 object,您必须首先获得对“公开”权限的引用。 Because permissions are exposed by other service principals.
因为权限是由其他服务主体公开的。
as I cannot upload whole file, here is a PowerShell script that creates a sample application with required permission to some MS Graph and some Power BI permissions.因为我无法上传整个文件,所以这里是一个 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
The interesting parts are around "apppermissionrequired" and "targetserviceprincipalname" variables.有趣的部分是围绕“apppermissionrequired”和“targetserviceprincipalname”变量。
I can't reply to Rolfo's comment directly as I don't have enough clout yet.我无法直接回复 Rolfo 的评论,因为我还没有足够的影响力。 While it's true it's not dead simple, it's possible to use both in the same session as of July 2021. Not sure this was always the case, or something was updated to allow it.
确实,这并不简单,但截至 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
UPDATE更新
With the new Graph API we can use the following command to add API permissions to an App Registration/Service Principal using PowerShell. It's much simpler than the old process.使用新的图形 API,我们可以使用以下命令将 API 权限添加到使用 PowerShell 的应用程序注册/服务主体。它比旧过程简单得多。
Add-AzADAppPermission -ApplicationId "$spId" -ApiId "00000009-0000-0000-c000-000000000000" -PermissionId "7504609f-c495-4c64-8542-686125a5a36f"
(This is the case for the PowerBI API) (PowerBI API就是这种情况)
If deploying via an Azure Devops Pipeline I often recommend using the following script to authenticate into AAD:如果通过 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.