微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法使用 Poweshell 上的私有证书连接到 Exchange Online

如何解决无法使用 Poweshell 上的私有证书连接到 Exchange Online

我正在尝试使用下一个流程创建 powershell 脚本。

  1. 通过应用程序登录到 Azure Active Directory。
  2. 创建私有证书。
  3. 将证书上传到 Azure AD 应用程序证书。
  4. 连接到 ExchangeOnline。

为此,我根据以下步骤创建了下一个脚本: 第一步:

$clientId = 'xxx'
$tenantId = 'xxx'
$clientSecret = 'xxx'
$org = 'xxx.onmicrosoft.com'
$clientSecret = ConvertTo-securestring $clientSecret -AsPlainText -Force
$credobject = New-Object System.Management.Automation.PSCredential ($clientId,$clientSecret)
Connect-AzAccount -Credential $credobject -Tenant $tenantId -ServicePrincipal

第 2 步和第 3 步:

$cert = New-SelfSignedCertificate -DnsName $org -NotAfter (Get-Date).AddYears(1) -KeySpec KeyExchange
$binCert = $cert.GetRawCertData()
$credValue = [System.Convert]::ToBase64String($binCert)
$validFrom = [datetime]::Parse($cert.GetEffectiveDateString())
$validTo = [datetime]::Parse($pfx.GetExpirationDateString())
$validTo = $validTo.AddDays(-1);
New-AzADAppCredential -ApplicationId $clientId -CertValue $credValue -StartDate $validFrom -EndDate $validTo

到目前为止一切顺利。我可以在应用程序的证书列表中看到此证书。 但是当我要使用以下命令连接到 MS Exchange Online 时:

Connect-ExchangeOnline -Certificate $cert -AppID $clientId -Organization $org

我得到下一个问题:

{
   "error":"invalid_client","error_description":"xxx: Client assertion contains an invalid signature. [Reason - The key used is expired.,Thumbprint of key used by client: 'xxx',Found key 'Start=03/11/2021 14:59:26,End=03/11/2022 13:09:26',Please visit the Azure Portal,Graph Explorer or directly use MS Graph to see configured keys for app Id 'xxx'. Review the documentation at https://docs.microsoft.com/en-us/graph/deployments to determine the corresponding service endpoint and https://docs.microsoft.com/en-us/graph/api/application-get?view=graph-rest-1.0&tabs=http to build a query request URL,such as 'https://graph.microsoft.com/beta/applications/xxx']\r\nTrace ID: xxxx\r\nCorrelation ID: xxx\r\nTimestamp: 2021-03-11 13:15:28Z","error_codes":[
      700027
   ],"timestamp":"2021-03-11 13:15:28Z","trace_id":"xxx","correlation_id":"xxx","error_uri":"https://login.microsoftonline.com/error?code=700027"
}

但是这个新创建的证书不能过期。我会很高兴看到任何想法。堆积了几天。

编辑: 我还承认,如果我使用 UI 上传新创建的证书但不使用此命令:

New-AzADAppCredential -ApplicationId $clientId -CertValue $credValue -StartDate $validFrom -EndDate $validTo

然后我可以用新创建的证书在线交换

解决方法

问题出在 $validTo = $validTo.AddDays(-1); 上。因此,$validTo 早于 $cert.NotAfter

请像这样修改脚本:

$cert = New-SelfSignedCertificate -DnsName $org -CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date).AddYears(1) -KeySpec KeyExchange
$binCert = $cert.GetRawCertData()
$credValue = [System.Convert]::ToBase64String($binCert)
New-AzADAppCredential -ApplicationId $clientId -CertValue $credValue -StartDate $cert.NotBefore -EndDate $cert.NotAfter

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。