[英]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.