将Powershell Exchange EWS脚本身份验证转换为Oauth获取错误:访问群体声明值对当前资源无效



我正在尝试将一些现有的Exchange Online EWS脚本转换为使用Oauth。我可以请求访问令牌,但当我尝试使用邮箱时,会出现以下错误。我感谢你的帮助!

x-ms-不可知论者:2000003;reason="受众声明值对当前资源无效。受众声明为'https://graph.microsoft.com',请求url为'https://outlook.office365.com/EWS/Exchange.asmx,资源类型为"Exchange"。";error_category="invalid_resource">

这是代码:

## Request an access token
# Define AppId, secret and scope, your tenant name and endpoint URL
$AppId = 'APP-ID HERE'
$AppSecret = 'SECRET HERE'
$Scope = "https://graph.microsoft.com/.default"
$TenantName = "OurDomain.onmicrosoft.com"
$Url = "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token"
# Add System.Web for urlencode
Add-Type -AssemblyName System.Web
# Create body
$Body = @{
client_id = $AppId
client_secret = $AppSecret
scope = $Scope
grant_type = 'client_credentials'
}
# Splat the parameters for Invoke-Restmethod for cleaner code
$PostSplat = @{
ContentType = 'application/x-www-form-urlencoded'
Method = 'POST'
# Create string by joining bodylist with '&'
Body = $Body
Uri = $Url
}
# Request the token!
$Request = Invoke-RestMethod @PostSplat
#######################
# Import "Microsoft Exchange Web Services Managed API 2.2"
Import-Module -Name "C:Program FilesMicrosoftExchangeWeb Services2.2Microsoft.Exchange.WebServices.dll"
## Create the Exchange Service object with Oauth creds
$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2013_SP1
$service.Url= new-object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
$Service.TraceEnabled = $true
$Service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.OAuthCredentials($Request.access_token)
#####################
$Email = "UserA@OurDomain.com"
# Set the WellKnownFolder
$FolderId = [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox
# Bind to WellKnownFolder Notes
$folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($Service, $folderId)
Write-Host "$($Email): $($folderName):  " -NoNewline 
$folder.archivetag.RetentionId.Guid     

在您的脚本中,您需要将范围从更改为原始范围

$Scope = "https://graph.microsoft.com/.default"

$Scope = "https://outlook.office365.com/.default"

你的代码的其余部分没有使用Graph,所以你不需要为你没有使用的东西获取访问令牌。此外,由于您使用的是App Secret,您将生成一个App Only令牌,这意味着您无论如何都不会有刷新令牌。您的EWS代码中缺少的两件事是,您需要使用EWS模拟,并且您还应该始终设置X-AnchorMailbox标头,例如您将具有

$service.HttpHeaders.Add("X-AnchorMailbox", "mailboxtoaccess@domain.com")
$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, "mailboxtoaccess@domain.com")

最新更新