Powershell-执行“授予权限" Powershell对Azure AD应用程序执行的操作 [英] Powershell - Do "Grant Permissions" action on Azure AD Application with Powershell
问题描述
我正在使用AzureAD模块创建一个Azure AD应用程序来调用Microsoft Graph API.我可以成功生成访问令牌.但是,当我尝试调用API时,出现错误消息":无效的范围声明/角色.".
I'm creating an Azure AD application using AzureAD module to call Microsoft Graph API. I can successfully generate the access token. But, when I try to call the API I have an error "message": "Invalid scope claims/roles.".
当我在Azure门户中创建的应用程序中单击授予权限"按钮并重试对API的调用时,该调用正在工作.
When I click on "Grant Permissions" button in my created application in Azure Portal and retry the call to API, the call is working.
我在任何地方都找不到如何使用Powershell进行此授予权限"操作.有办法吗?
I don't find anywhere how to do this "Grant Permissions" actions with Powershell. Is there a way to do that ?
谢谢
达明(Damien)
推荐答案
有一种简便的方法(以管理员身份),它要求您为Powershell安装了AzureAD和AzureRM模块,并且不受Microsoft的支持.
There is an easy way to do this (as admin), it requires you have the AzureAD and AzureRM modules installed for Powershell and is not supported by Microsoft.
Original post / reference to my blog is here: http://www.lieben.nu/liebensraum/2018/04/how-to-grant-oauth2-permissions-to-an-azure-ad-application-using-powershell-unattended-silently/
应该帮助您完成此操作的特定代码示例:
The specific code sample that should help you accomplish this:
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
}
这篇关于Powershell-执行“授予权限" Powershell对Azure AD应用程序执行的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!