Convert Powershell Exchange EWS script authentication to Oauth getting error: The audience claim value is invalid for current resource

Convert Powershell Exchange EWS script authentication to Oauth getting error: The audience claim value is invalid for current resource

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

x-ms-diagnostics: 2000003;reason="受众声明值对当前资源无效。受众声明为'https://graph.microsoft.com', request url is '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 Files\Microsoft\Exchange\Web Services.2\Microsoft.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 header 例如您会

$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")