我正在编写应用程序,它需要使用IMAP读取邮箱,但作为守护进程,不需要用户交互。我需要使用OAuth2来访问。因为我需要它而不需要用户交互,所以我需要使用客户端凭据流。这是今年六月增加的。
从正式文件开始,我做了所有的事情。注册应用程序、添加权限、使用PowerShell添加邮箱权限。
当我得到具有作用域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代替电子邮件地址作为用户名,但没有成功。
我不知道我在哪里犯了这个错误,我是否使用了正确的用户名。任何帮助都是非常感谢的。
发布于 2022-07-29 12:26:32
我写了同样的答案这里,所以我在这里处理它。
我想我取得了一些进展。
我读了几次文档,从一开始就用同样的错误尝试了几次。我甚至尝试使用客户端和对象I,而不是电子邮件作为用户名,因为没有更好的想法。
这就是我以前犯过错误的地方。
在需要注册服务主体的部分,我需要执行
New-ServicePrincipal -AppId <APPLICATION_ID> -ServiceId <OBJECT_ID> [-Organization <ORGANIZATION_ID>]在这里,我将企业应用程序对象id作为ServiceId参数。这也没问题。
但继续
Add-MailboxPermission -Identity "email address removed for privacy reasons" -User
<SERVICE_PRINCIPAL_ID> -AccessRights FullAccess我已将已注册的应用程序对象id作为用户参数。我也尝试过设置企业应用程序的对象id,但没有成功。
当我被处决时
Get-ServicePrincipal -Organization <ORGANIZATION_ID> | fl我没有注意ServiceId属性,即使文档指定了它,并且说它将是不同的。
现在我把一切都清理干净,重新开始。
我再次执行了所有步骤,但在创建新服务主体的步骤中,我使用了企业应用程序视图中的数据。当我需要添加邮件权限时,我列出服务主体,然后从输出中使用ServiceId值作为用户的参数。
有了这个,我才能授权。
发布于 2022-09-12 11:39:43
感谢大家分享你们的经验。事实证明,这有点令人困惑。:)
总之,使用IMAPS和OAuth2访问邮箱(而不是使用Graph,这是Microsoft推荐的另一种方法):
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/.defaulthttps://stackoverflow.com/questions/73138484
复制相似问题