我一直在努力尝试使用 PowerShell 访问 Microsoft Graph。
首先我尝试使用 authorization flow和 Invoke-WebRequest
和 Invoke-RestMethod
我都无法开始工作。
然后我找到this blog展示了如何使用 PowerShell 和几个 Azure 模块来实现。下面是我正在使用的代码(直接从该博客中截取),但每次我访问 Invoke-RestMethod
(在 do-while 循环中)而不是获取查询结果时,我得到403 禁止错误
:
Invoke-RestMethod : The remote server returned an error: (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 、刷新 token 等,并且 $token.CreateAuthorizationHeader()
也返回了正确的授权 = 承载 token
我以前从未对 Microsoft Graph 做过任何事情,所以我确定我做错了什么,但我终究无法弄清楚是什么。
最佳答案
您不能重复使用该博文中的 clientid
。您需要通过注册您的应用程序来获取您自己的clientid
。参见 Register your app with the Azure AD v2.0 endpoint有关如何注册您的应用程序的详细信息。
关于powershell - 使用 PowerShell 访问 Microsoft Graph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547754/