- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试查找有关如何使用 PowerShell 对 EWS 实现非交互式 Oauth2 身份验证的文档,但我可能没有使用正确的搜索词,因为我找不到任何有用的信息。我可以在 OAuth2 上找到的 Microsoft 文档只有 C# 文档。
那么,有谁知道如何实现这一点?
最佳答案
在以下博客中有一个非常好的概述:
https://ingogegenwarth.wordpress.com/2018/08/02/ews-and-oauth/#more-5139
我使用上面的博客让它在我们的 PowerShell 脚本中工作 - 经过大量试验和错误。以下示例脚本使用在 Azure AD 中注册的应用程序的 ClientID。如果尚未在 Azure AD 中注册应用程序,则必须先执行此操作。 Web 上有各种指南可用于在 Azure AD 中注册新应用程序。为了通过 OAuth 使用 EWS,您注册的应用程序必须在 Azure AD 中具有正确的权限。 EWS 有两种选择:
#Variables
$UserPrincipalName = "Enter the UPN of your Service Account ID"
$Password = "Password of your Service Account ID - store this securely"
$ClientIDfromAzureAD = "Client ID of your registered application in Azure AD"
$errRecip = "Email address of recipients to notify via email if errors occur"
$script = "Name of script"
$sender = "Email address of sender - normally the server name where your script runs"
$logfile = "Path and filename to log file"
$smtpServer = "Your SMTP server"
Function Get-EWSOAuthToken
{
<#
.SYNOPSIS
Request an OAuth EWS token from Azure AD using supplied Username and Password
.DESCRIPTION
Request an OAuth EWS token from Azure AD using supplied Username and Password
.PARAMETER UserPrincipalName
The UPN of the user that will authenticate to Azure AD to request the OAuth Token
.PARAMETER Password
The Password (SecureString) of the user that will authenticate to Azure AD to request the OAuth Token
.PARAMETER ADALPath
The full path and filename on the local file system to the ADAL (Active Directory Authentication Library) DLL. This library is installed as part of various modules such as Azure AD, Exchange Online, etc.
.PARAMETER ClientId
Identifier of the client application that is requesting the token. You must register your calling application in Azure AD. This will provide you with a ClientID and RedirectURI
.PARAMETER ConnectionUri
The URI of the Exchange Online EWS endpoint. Default URI of 'https://outlook.office365.com/EWS/Exchange.asmx' is used
.PARAMETER RedirectUri
Address to return to upon receiving a response from the authority. You must register your calling application in Azure AD. This will provide you with a ClientID and RedirectURI
.EXAMPLE
$token = Get-EWSOAuthtokenFromCredential -UserPrincipalName "ABC123@mydomain.com" -Password $mySecurePassword -ClientId "123444454545454767687878787" -RedirectUri "https://dummyredirectdomain.com"
$ews = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2013_SP1 -ErrorAction Stop
$ews.UseDefaultCredentials = $False
$ews.Credentials = [Microsoft.Exchange.WebServices.Data.OAuthCredentials]$token
#>
[CmdletBinding()]
Param
(
[System.String]$UserPrincipalName,
[System.Security.SecureString]$Password,
[System.String]$ADALPath,
[System.String]$ClientId = "123444454545454767687878787",
[System.Uri]$ConnectionUri = "https://outlook.office365.com/EWS/Exchange.asmx",
[System.Uri]$RedirectUri = "https://dummyredirectdomain.com"
)
Begin
{
Write-Host "Starting Get-EWSOAuthTokenFromCredential function..." -ForegroundColor Yellow
#Determine ADAL location based on Azure AD module installation path
If([System.String]::IsNullOrEmpty($ADALPath))
{
Write-Host "Attempting to locate ADAL library..." -ForegroundColor Yellow
$ADALPath = (Get-InstalledModule -Name "AzureAD" -ErrorAction SilentlyContinue | Select-Object InstalledLocation).InstalledLocation
$ADALPath = Join-Path -Path $ADALPath -ChildPath "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
Write-Host "Located library @ '$ADALPath'" -ForegroundColor Yellow
If([System.String]::IsNullOrEmpty($ADALPath))
{
#Get List of installed modules and check Azure AD DLL is available
$tmpMods = Get-Module -ListAvailable | Where-Object {$_.Name -eq "AzureAD"}
If($tmpMods)
{
$ADALPath = Split-Path $tmpMods.Path
$ADALPath = Join-Path -Path $ADALPath -ChildPath "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
Write-Host "Located library @ '$ADALPath'" -ForegroundColor Yellow
}
Else
{
$err = "$($myinvocation.mycommand.name) requires the ADAL Library DLL files ('Microsoft.IdentityModel.Clients.ActiveDirectory.dll') that are installed as part of the 'AzureAD' module! Please install the AzureAD module from the Powershell Gallery. See: 'https://www.powershellgallery.com/packages/AzureAD' for more information"
Throw "$err"
}
}
}
#Load 'Microsoft.IdentityModel.Clients.ActiveDirectory' DLL
Try
{
Import-Module $ADALPath -DisableNameChecking -Force -ErrorAction Stop
Write-Host "Successfully imported ADAL Library" -ForegroundColor Yellow
}
Catch
{
$err = "$($myinvocation.mycommand.name): Could not load ADAL Library DLL '$ADALPath'. Error: $_"
Throw "$err"
}
}
Process
{
try
{
$resource = $connectionUri.Scheme + [System.Uri]::SchemeDelimiter + $connectionUri.Host
$azureADAuthorizationEndpointUri = "https://login.windows.net/common/oauth2/authorize/"
$AuthContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($azureADAuthorizationEndpointUri) -ErrorAction Stop
$AuthCredential = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential($UserPrincipalName, $Password) -ErrorAction Stop
Write-Host "$($myinvocation.mycommand.name): Requesting a new OAuth Token..." -ForegroundColor Yellow
$authenticationResult = ([Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($AuthContext, $resource, $clientId, $AuthCredential))
If ($authenticationResult.Status.ToString() -ne "Faulted") {
Write-Host "$($myinvocation.mycommand.name): Successfully retrieved OAuth Token" -ForegroundColor Yellow
}
else {
$err = "$($myinvocation.mycommand.name): Error occurred calling ADAL 'AcquireTokenAysnc' : $authenticationResult.Exception.ToString()"
Throw "$err"
}
}
catch
{
#create object
$returnValue = New-Object -TypeName PSObject
#get all properties from last error
$ErrorProperties =$Error[0] | Get-Member -MemberType Property
#add existing properties to object
foreach ($Property in $ErrorProperties)
{
if ($Property.Name -eq 'InvocationInfo')
{
$returnValue | Add-Member -Type NoteProperty -Name 'InvocationInfo' -Value $($Error[0].InvocationInfo.PositionMessage)
}
else
{
$returnValue | Add-Member -Type NoteProperty -Name $($Property.Name) -Value $($Error[0].$($Property.Name))
}
}
#return object
$returnValue
break
}
}
End
{
return $authenticationResult
}
}
###### Main script
#Ensure TLS 1.2 protocol is enabled
try {
If ([Net.ServicePointManager]::SecurityProtocol -notmatch 'Tls12') {
[Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
Write-Host "Enabled Tls1.2 in '[Net.ServicePointManager]::SecurityProtocol'" -ForegroundColor Yellow
}
else {
Write-Host "Tls1.2 is enabled in '[Net.ServicePointManager]::SecurityProtocol'" -ForegroundColor Yellow
}
}
Catch {
$err = "An error occurred enabling TLS1.2. Error: $_"
Write-Host "`n$err" -ForegroundColor Red
Send-MailMessage -To $errRecip -Subject "$script - Error occurred during processing" -Body $err -From $sender -Attachment $logfile -SmtpServer $smtpServer
Exit
}
#CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
$EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending | Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
If (Test-Path $EWSDLL)
{
Try
{
Import-Module $EWSDLL -DisableNameChecking -ErrorAction Stop
}
Catch
{
$err = "An error occurred importing the Exchange Web Services DLL '$EWSDLL'. Error: $_"
Write-Host "`n$err" -ForegroundColor Red
Send-MailMessage -To $errRecip -Subject "$script - Error occurred during processing" -Body $err -From $sender -Attachment $logfile -SmtpServer $smtpServer
Exit
}
}
Else
{
$err = "This script requires the EWS Managed API 1.2 or later. Please download and install the current version of the EWS Managed API from http://go.microsoft.com/fwlink/?LinkId=255472"
Write-Host "`n$err" -ForegroundColor Red
Send-MailMessage -To $errRecip -Subject "$script - Error occurred during processing" -Body $err -From $sender -Attachment $logfile -SmtpServer $smtpServer
Exit
}
#Create EWS Object
$ews = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList "Exchange2013_SP1" -ErrorAction Stop
#Authenticate EWS using OAuth
Try {
$ews.UseDefaultCredentials = $False
Write-Host "Requesting EWS OAuth Token using registered Client ID" -ForegroundColor Yellow
$OAuthResult = Get-EWSOAuthToken -UserPrincipalName $UserPrincipalName -Password $Password -ClientId "$ClientIDfromAzureAD" -ErrorAction Stop
$token = $OAuthResult.Result.AccessToken
#Check if we successfully retrieved an Oauth Token
If ([System.String]::IsNullOrEmpty($token))
{
$err = "Get-EWSOAuthtoken returned an empty Auth Token. Aborted. Latest error details:`n$_error $($OAuthResult.Exception)"
Write-Host "`n$err" -ForegroundColor Red
$OAuthResult | Format-List -Force
$OAuthResult.Result | Format-List -Force
Send-MailMessage -To $errRecip -Subject "$script - Error occurred during processing" -Body "$err" -From $sender -Attachment $logfile -SmtpServer $smtpServer
Exit
}
else
{
$OAuthchk = $true
$ews.Credentials = [Microsoft.Exchange.WebServices.Data.OAuthCredentials]$token
Write-Host "Set EWS credentials to OAuth token" -ForegroundColor Yellow
}
}
Catch
{
$err = "An error occurred creating a new EWS object. Error:`n $_"
write-host "`n$err" -ForegroundColor Red
Send-MailMessage -To $errRecip -Subject "$script - Error occurred during processing" -Body "$err" -From $sender -Attachment $logfile -SmtpServer $smtpServer
Exit
}
# Do your processing using EWS
....
关于Powershell、EWS、OAuth2 和自动化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58169831/
我正在为 Exchange 服务器开发电子邮件客户端.......我遇到了 EWS 和 EWS 托管 API。请帮助我了解我应该去哪一个? 最佳答案 如果你是: 使用 .Net 并且该功能在 EWS
有没有人知道使用 EWS 托管 API 在单个 EWS 调用中绑定(bind)到多个项目的任何方法,只给出相关项目的 ItemIds? 这是我的应用程序目前的工作方式: 反复调用 ExchangeSe
我正在尝试创建一个项目来使用 EWS 服务收听 Exchange 房间邮箱中的事件。 如果我们需要监控 20k 个邮箱,那么我们需要创建 20k 个打开的连接。而不是 EWS 允许我们在每个组中创建最
是否可以通过EWS获取用户的TimeZone和工作时间? 我能够为当前用户(用于初始化 ExchangeService 的帐户)提取 TZ 和工作时间 UserConfiguration usrCon
Exchange Web 服务 FindItems()调用有一些重载占用 SearchFilter object 和其他采用高级查询语法 (AQS) 的查询字符串。目前,我接受来自调用者对我的代码的
我使用 EWS 获取交换电子邮件,但如何从电子邮件正文中获取纯文本而不使用 html? 现在我用这个: EmailMessage item = (EmailMessage)outbox.Items[i
Note: This particular issue has significant impact on our customers, which translates to high busine
我的预约会重复一周。通过使用下面的代码行: FindItemsResults results = folder.findAppointments(cView); 结果返回同一约会的所有出现,我只想为每
这个问题已经有答案了: How to identify object types in java [duplicate] (4 个回答) 已关闭 7 年前。 我正在研究 EWS java api,我想
我可以成功实现 Restful 推送通知。我从 Exchange-server 2010 sp1 收到此通知:
我有以下代码: (交流预约中的会面) For Each Recipient As String In emailAdresses For i As Integer = 0 To Meeting
我尝试编写一个控制台应用程序,它将使用 EWS 建立与邮箱的连接,然后在每次收到新电子邮件时打印一行。 一旦我完成这项工作,最终结果就是将其变成一项服务,并且每次电子邮件到达某个邮箱时都会创建一个任务
我正在使用 EWS 托管 API 2.0。我希望将来能够搜索日历以交换约会的主题。 注意事项是: 只返回与主题=“测试”匹配的 future 约会 仅返回 future 90 天内的约会 我可以让 C
我正在使用 Exchange Web 服务来尝试获取所有未完成的 Outlook 任务的列表。 我有一个 ExchangeService 实例,并尝试像这样查找所有未完成的任务: SearchFilt
我想通过 EWS 删除 Appointments 但它不起作用。我有以下代码: private void deleteAppointment(object obj) { ServicePoin
这个问题在这里已经有了答案: Wrong mailbox items being retrieved using Exchange Web Services managed API in C# (2
我正在使用 Exchange Web Services Managed API 2.2 来监控用户收件箱,并且需要确定电子邮件是新邮件、回复邮件还是转发邮件。 我看过关于 SO 的各种文章,例如 ho
这可能是一个非常基本的问题,但我还没有找到任何答案。我在 Windows 服务中使用 Exchange Web 服务来监视通过请求订阅发送到我们的 Exchange 2010 服务器的新邮件。它工作得
我正在尝试使用 C# EWS 2.0 库列出一些事件。 它使用以下代码: public IEnumerable ListEvents(CalendarFolder folder, DateTi
如何使用 Java EWS 库指定 SearchFilter 来获取包含已定义主题行的邮件? 提前致谢。 最佳答案 假设您指的是 Microsoft 创建的库,这里是直接来自下载中包含的 EWS Ja
我是一名优秀的程序员,十分优秀!