【发布时间】:2018-01-31 17:11:34
【问题描述】:
我一直在尝试使用 PowerShell 访问 Microsoft Graph。
首先我尝试使用authorization flow 和Invoke-WebRequest 和Invoke-RestMethod,我都无法开始工作。
然后我找到了this blog,它展示了如何使用 PowerShell 和几个 Azure 模块进行操作。下面是我正在使用的代码(直接从该博客中提取),但每次我到达 Invoke-RestMethod(在 do-while 循环中)而不是得到查询结果时,我都会得到 403 Forbidden error:
Invoke-RestMethod : 远程服务器返回错误:(403) Forbidden。
Function GetAuthToken {
Param (
[Parameter()]
$TenantName
)
Import-Module Azure
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$resourceAppIdURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/$TenantName"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$Credential = Get-Credential
$AADCredentialUser = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName, $credential.Password
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $AADCredentialUser)
Write-Output $authResult
}
Function GetAllObjectOfType {
param
(
[Parameter(Mandatory = $true)]
$Tenant,
[Parameter(Mandatory = $true)]
$Type,
[Parameter(Mandatory = $false)]
$BatchSize = 100,
[Parameter(Mandatory = $false)]
$Version = 'Beta'
)
#------Get the authorization token------#
$token = GetAuthToken -TenantName $tenant
#------Building Rest Api header with authorization token------#
$authHeader = @{
'Content-Type' = 'application/json'
'Authorization' = $token.CreateAuthorizationHeader()
}
#------Initial URI Construction------#
#$uritest = "https://graph.microsoft.com/v1.0/users/user@contoso.com/mailFolders/Inbox/childFolders"
$uritest = "https://graph.microsoft.com/v1.0/me/mailFolders/Inbox"
#Join-Path -Path ''
$ObjCapture = @()
do {
$users = Invoke-RestMethod -Uri $uritest -Headers $authHeader -Method Get
$FoundUsers = ($Users.value).count
write-host "URI" $uri " | Found:" $FoundUsers
#------Batched URI Construction------#
$uri = $users.'@odata.nextlink'
$ObjCapture = $ObjCapture + $users.value
}until ($uri -eq $null)
$ObjCapture
}
我可以从 Graph Explorer 运行同样的查询 (/v1.0/me/mailFolders/Inbox),它运行得非常好,没有错误。
GetAuthToken 似乎正在工作,因为我确实得到了一个带有过期、刷新令牌等的令牌,$token.CreateAuthorizationHeader() 也返回了正确的Authorization = Bearer token
我以前从未对 Microsoft Graph 做过任何事情,所以我确信我做错了什么,但我终生无法弄清楚是什么。
【问题讨论】:
-
您能否添加您收到的令牌以及您为获得
clientId所采取的步骤(包括范围/权限)? -
@MarcLaFleur-MSFT 实际上,
clientId与我从中获得步骤的文章中使用的相同(所以我假设这是不正确的)。我不确定我可以添加令牌是什么意思。将其添加到评论中?
标签: powershell microsoft-graph-api