首页 > 解决方案 > 通过 OAuth 与 PowerShell 中的 EWS 的应用程序机密进行身份验证

问题描述

我正在寻找正确的 PowerShell 代码,以了解如何通过 OAuth 仅使用应用程序密码而不是用户名和密码对 EWS 进行身份验证。我将应用注册设置为具有 full_access_as_app 权限。用例是应用程序运行是一个守护进程,它根据提供的地址发送电子邮件。来自用户的远程用户未在系统中进行身份验证,因此处理发送电子邮件的进程无法通过 OAuth 对其进行身份验证。

我发现这很有帮助,所以我假设只需要更改获取令牌的部分:Powershell、EWS、OAuth2 和自动化

标签: powershelloauthoffice365exchangewebservices

解决方案


您可以采用几种不同的方法,例如,如果您使用的 MSAL 库与您指向的脚本所使用的 ADAL 不同,那么您可以执行类似的操作。

$ClientId = "9d5d77a6-xxxx-473e-8931-958f15f1a96b"
$MailboxName = "gscales@domain.com"
$RedirectUri = "msal9d5d77a6-fe09-473e-8931-958f15f1a96b://auth"
$ClientSecret = "xxx";
$Scope = "https://outlook.office365.com/.default"
$TenantId = (Invoke-WebRequest https://login.windows.net/datarumble.com/v2.0/.well-known/openid-configuration | ConvertFrom-Json).token_endpoint.Split('/')[3]
$app =  [Microsoft.Identity.Client.ConfidentialClientApplicationBuilder]::Create($ClientId).WithClientSecret($ClientSecret).WithTenantId($TenantId).WithRedirectUri($RedirectUri).Build()
$Scopes = New-Object System.Collections.Generic.List[string]
$Scopes.Add($Scope)
$TokenResult = $app.AcquireTokenForClient($Scopes).ExecuteAsync().Result;

推荐阅读