如何在PowerShell中正确访问REST API v2.0进行邮箱管理

时间:2019-01-14 05:38:15

标签: powershell outlook-restapi

我们有一个PowerShell脚本,该脚本检查服务邮箱并使用信息更新壁板,然后将相关电子邮件移至已删除的文件夹。这是在API v1.0下设置的,现已弃用,我们需要针对2.0版进行更改。

不幸的是,这导致了很多混乱和很多头刮伤,这不是很有趣。发生这种情况主要是围绕获取oAuth2令牌,然后将其馈入邮箱请求。

到目前为止,我们已经成功注册了Azure AD应用,并且它提供了身份验证令牌,但是从Microsoft Graph回来却是未经授权的。

# tenantID, clientSecret and clientID not here.

# The resource URI
$resource = "https://graph.microsoft.com"
# Your Client ID and Client Secret obainted when registering your WebApp

$redirectUri = "http://returnuri"

# UrlEncode the ClientID and ClientSecret and URL's for special characters 
$clientIDEncoded = [System.Web.HttpUtility]::UrlEncode($ClientID)
$clientSecretEncoded = [System.Web.HttpUtility]::UrlEncode($clientSecret)
$redirectUriEncoded =  [System.Web.HttpUtility]::UrlEncode($redirectUri)
$resourceEncoded = [System.Web.HttpUtility]::UrlEncode($resource)
$scopeEncoded = [System.Web.HttpUtility]::UrlEncode("https://outlook.office.com/user.readwrite.all")

$body = @"
client_id=$ClientID
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=$clientSecretEncoded
&grant_type=client_credentials
"@

$userid = 'userID'

$accessToken = Invoke-RestMethod "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token" -Method Post -Body $body
#
#$cred = $(Get-Credential)

Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$userid/messages" -Headers @{Authorization = "Bearer $($accessToken.access_token)"} -Credential $cred

预期结果:访问邮箱。

实际结果:

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
At line:32 char:1
+ Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$useri ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation:     (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

0 个答案:

没有答案