[英]Microsoft exchange - IMAP OAuth2 With client credentials
我正在編寫需要使用 IMAP 讀取郵箱的應用程序,但作為守護進程,無需用戶交互。 我需要使用 OAuth2 來獲得訪問權限。 因為我需要它而不需要用戶交互,所以我需要使用客戶端憑據流。 這是今年六月添加的。
我已經完成了官方文檔中的所有內容。 使用 PowerShell 注冊應用程序,添加權限,添加郵箱權限。
當我使用 scope https://outlook.office365.com/.default
獲得請求訪問令牌時,我認為我收到的那個角色是正確的IMAP.AccessAsApp
,所以我認為是正確的。 我使用https://jwt.ms/來解析 JWT。
問題是當我嘗試在 Java 中使用此訪問令牌進行身份驗證時,例如
Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
props.put("mail.debug", "true");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
store.connect("outlook.office365.com", 993, "testing@mydomain.com", "accessToken");
我收到AUTHENTICATE failed
。 我嘗試了與使用授權代碼流接收的訪問令牌相同的代碼,這需要用戶交互。 使用該訪問代碼,我能夠連接到郵箱。 所以代碼是正確的。
我什至嘗試使用客戶端 ID 和服務 ID 而不是 email 地址作為用戶名,但沒有成功。
我不確定我在哪里犯了錯誤,以及我是否使用了正確的用戶名。 任何幫助表示贊賞。
我在這里寫了同樣的答案,所以我在這里應對。
我想我取得了一些進展。
我讀了幾次文檔,從一開始就嘗試了幾次同樣的錯誤。 我什至嘗試使用客戶端和 object id 而不是 email 作為用戶名,但缺乏更好的想法。
所以這就是我認為我以前犯過錯誤的地方。
在需要注冊服務主體的部分,我需要執行
New-ServicePrincipal -AppId <APPLICATION_ID> -ServiceId <OBJECT_ID> [-Organization <ORGANIZATION_ID>]
在這里,我將企業應用程序 object id 作為 ServiceId 參數。 沒關系。
但是在
Add-MailboxPermission -Identity "email address removed for privacy reasons" -User
<SERVICE_PRINCIPAL_ID> -AccessRights FullAccess
我已將我注冊的應用程序 object id 作為用戶參數。 我也試過設置企業應用程序的object id,但沒有成功。
當我執行
Get-ServicePrincipal -Organization <ORGANIZATION_ID> | fl
我沒有注意 ServiceId 屬性,即使有文檔指定它並說它會有所不同。
現在我清除了一切,重新開始。
我已經再次執行了所有步驟,但是在創建新服務主體的步驟中,我使用了來自企業應用程序視圖的數據。 當我需要添加郵件權限時,我列出服務主體,然后使用 output 中的ServiceId
值作為用戶的參數。
有了這個,我就可以授權了。
感謝大家分享您的經驗。 事實證明,這有點令人困惑。 :)
總而言之,使用 IMAPS 和 OAuth2 訪問郵箱(而不是使用微軟推薦的另一種方法 Graph API):
Connect-AzureAD
Connect-ExchangeOnline
$azapp = Get-AzureADApplication -SearchString 'App Registration Name'
$azsp = Get-AzureADServicePrincipal -SearchString $azapp.DisplayName
# GOTCHA: You need the ObjectId from 'Enterprise applications' (Get-AzureADServicePrincipal), not 'Application registrations' (Get-AzureADApplication) for ServiceId (thanks @[jamie][1])
$sp = New-ServicePrincipal -AppId $azapp.AppId -ServiceId $azsp.ObjectId -DisplayName "EXO Service Principal for $($azapp.DisplayName)"
$mbxs = 'mymbx1@yourdomain.tld',`
'mymbx2@yourdomain.tld',`
'mymbx3@yourdomain.tld'
$mbxs | %{ Add-MailboxPermission -Identity $_ -User $sp.ServiceId -AccessRights FullAccess } | fl *
Get-MailboxPermission $mbxs[-1] | ft -a
您可以使用Get-IMAPAccessToken.ps1來測試您的設置
.\Get-IMAPAccessToken.ps1 -TenantID $TenantId -ClientId $ClientId -ClientSecret $ClientSecret -TargetMailbox $TargetMailbox
您可能需要的其他參數:
https://login.microsoftonline.com/<YourTenantId>/
https://outlook.office365.com/.default
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.