问题在于网络服务帐户没有正确的访问权限来访问证书的私钥。
您可以通过两种方式解决这个问题。
第一个使用 powershell 和 setup.bat 来安装和配置证书。
在您的 Service Fabric 服务中,将 Setup.bat 添加到项目的根目录中。
编辑服务清单并添加一个设置入口点
<ExeHost> <Program>Setup.bat</Program> <WorkingFolder>CodePackage</WorkingFolder> </ExeHost>
bat 文件可能应该以更高的信任度运行。您可以在以下内容中添加申请清单在 ServiceManifestImport 内部:
<Policies> <RunAsPolicy CodePackageRef="Code" UserRef="SetupAdminUser" EntryPointType="Setup" /> </Policies>
在应用程序清单的底部(在 xml 的根目录中)添加以下内容以管理员身份运行。<Principals> <Users> <User Name="SetupAdminUser"> <MemberOf> <SystemGroup Name="Administrators" /> </MemberOf> </User> </Users> </Principals>
bat文件很简单:powershell.exe -ExecutionPolicy Bypass -Command ".\Scripts\Install-Certificates.ps1"
powershell 脚本可能如下所示
$pwd = ConvertTo-SecureString -String "YourPassword" -Force -AsPlainText
function Set-CertificatePermission
{
param
(
[Parameter(Position=1, Mandatory=$true)]
$cert ,
[Parameter(Position=2, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$serviceAccount
)
# Specify the user, the permissions and the permission type
$permission = "$($serviceAccount)","Read,FullControl","Allow"
$accessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission;
# Location of the machine related keys
$keyPath = $env:ProgramData + "\Microsoft\Crypto\RSA\MachineKeys\";
$keyName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName;
$keyFullPath = $keyPath + $keyName;
try
{
# Get the current acl of the private key
$acl = (Get-Acl $keyFullPath)
# Add the new ace to the acl of the private key
$acl.AddAccessRule($accessRule);
# Write back the new acl
Set-Acl -Path $keyFullPath -AclObject $acl;
}
catch
{
throw $_;
}
}
function Install-RootCA($path){
Write-Host "Installing root certificate"
Import-PfxCertificate -FilePath $path -CertStoreLocation "Cert:\LocalMachine\Root" -Password $pwd -Exportable
}
function Install-Certificate($path){
Write-Host "Installing certificate"
$cert = Import-PfxCertificate -FilePath $path -CertStoreLocation "Cert:\LocalMachine\My" -Password $pwd -Exportable
Set-CertificatePermission $cert "NT AUTHORITY\NETWORK SERVICE"
}
Install-RootCA ".\Certificates\CARoot.pfx"
Install-Certificate ".\Certificates\ClientCert.pfx"
这将在受信任的根存储中安装证书(因为我们使用自签名证书),并在计算机帐户的个人存储中安装证书。
Service Fabric 的重要一点是它还为网络服务访问私钥设置了正确的权限。
第二种方法:手动使用mmc
- 按 Windows 键 + R
- Type mmc
- 文件 => 添加/删除管理单元
- 添加证书
- 选择计算机帐户
- 右键单击“受信任的根证书颁发机构\证书”
- 导入根证书*.pfx(将其标记为可导出)
- 右键单击个人\证书
- 导入客户端证书*.pfx(将其标记为可导出)
- 右键单击导入的客户端证书:所有任务 => 管理私钥
- 添加网络服务作为用户并给予其完全控制权