Powershell-使用Powershell对Azure AD应用程序执行“授予权限”操作

Dam*_*lle 4 powershell azure azure-active-directory microsoft-graph

我正在使用AzureAD模块创建一个Azure AD应用程序来调用Microsoft Graph API。我可以成功生成访问令牌。但是,当我尝试调用API时,出现错误“消息”:“无效的范围声明/角色。”。

当我在Azure门户中创建的应用程序中单击“授予权限”按钮并重试对API的调用时,该调用正在运行。

我在任何地方都找不到如何使用Powershell进行此“授予权限”操作。有没有办法做到这一点 ?

谢谢

达米安

Jos*_*Jos 7

有一种简单的方法(以管理员身份),它要求您已为Powershell安装了AzureAD和AzureRM模块,并且不受Microsoft支持。

原始帖子/对我的博客的引用在这里:http : //www.lieben.nu/liebensraum/2018/04/how-to-grant-oauth2-permissions-to-an-azure-ad-application-using-powershell-无人值守/无声地/

可以帮助您完成此操作的特定代码示例:

Function Grant-OAuth2PermissionsToApp{
Param(
    [Parameter(Mandatory=$true)]$Username, #global administrator username
    [Parameter(Mandatory=$true)]$Password, #global administrator password
    [Parameter(Mandatory=$true)]$azureAppId #application ID of the azure application you wish to admin-consent to
)

$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
$res = login-azurermaccount -Credential $mycreds
$context = Get-AzureRmContext
$tenantId = $context.Tenant.Id
$refreshToken = @($context.TokenCache.ReadItems() | where {$_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date)})[0].RefreshToken
$body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
$apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
$header = @{
'Authorization' = 'Bearer ' + $apiToken.access_token
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
$url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$azureAppId/Consent?onBehalfOfAll=true"
Invoke-RestMethod -Uri $url -Headers $header -Method POST -ErrorAction Stop
}
Run Code Online (Sandbox Code Playgroud)